The server is Python and the client is Kotlin. When I send String from the server, String is printed from the client.
The simple code is here, but the client doesn't print it.
What could be the problem?
Server code
# server.py
import socket
from PyQt5.QtCore import QThread
host = '192.168.0.22'
port = 5000
server_sock = socket.socket(socket.AF_INET)
server_sock.bind((host, port))
server_sock.listen(1)
client_sock, addr = server_sock.accept()
print('Connected by', addr)
data="1234567"
client_sock.send(data.encode())
client_sock.close()
server_sock.close()
Client code
package com.cfsuman.client
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import java.io.DataInputStream
import java.net.Socket
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val thread = Thread(Runnable {
var socket = Socket("192.168.0.22", 5000)
var input = socket.getInputStream()
var dis = DataInputStream(input)
var data_input = dis.read()
println(data_input)
socket.close()
}).start()
}
}
Related
I have a python socket server that receives a string from an Android app and should return the same string in uppercase. The app can send the string and I receive it in the server but how could I receive the returned string in the Android studio?
Here is my python code:
import socket
HOST = "127.0.0.1" # Standard loopback interface address (localhost)
PORT = 65432 # Port to listen on (non-privileged ports are > 1023)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print(f"Connected by {addr}")
while True:
data = conn.recv(1024)
print(data)
if not data:
break
conn.sendall(data.upper())
Here is my sending message function
Socket s;
PrintWriter pw;
#Override
protected Void doInBackground(String... voids) {
String message = voids[0];
byte[] messageByte = new byte[1000];
boolean end = false;
String dataString = "";
try {
s = new Socket("10.0.2.2", Integer.parseInt("65432"));
//sending data
pw = new PrintWriter(s.getOutputStream());
pw.write(message);
pw.flush();
pw.close();
//////////
//receiving data
s.close();
} catch (IOException e) {
e.printStackTrace();
}
In my PowerShell script I SSL connect to windows server with the following code:
#SSL connecting to server
add-type #"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
public bool CheckValidationResult(
ServicePoint srvPoint, X509Certificate certificate,
WebRequest request, int certificateProblem) {
return true;
}
}
"#
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
$AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'
[System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols
How do I do it with Python script (without request me for a Certificate path)?
import socket
import ssl
# SET VARIABLES
packet, reply = "<packet>SOME_DATA</packet>", ""
HOST, PORT = 'XX.XX.XX.XX', 4434
# CREATE SOCKET
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(10)
# WRAP SOCKET
wrappedSocket = ssl.wrap_socket(sock, ssl_version=ssl.PROTOCOL_TLSv1, ciphers="ADH-AES256-SHA")
# CONNECT AND PRINT REPLY
wrappedSocket.connect((HOST, PORT))
wrappedSocket.send(packet)
print wrappedSocket.recv(1280)
# CLOSE SOCKET CONNECTION
wrappedSocket.close()
I am trying to connect my android app (client) to my PC (python server). They are both on the same network. I can ping my android phone from my PC and PC from phone. But when I try to connect them using sockets android app gets stuck at connecting and after a while throws a timeout exception.
Here is the code of Android Client class:
public class Client extends AsyncTask<Void, Void, Void> {
private String mCommand;
private String mHostIP;
public Client(String mCommand, String mHostIP) {
this.mCommand = mCommand;
this.mHostIP = mHostIP;
}
#Override
protected Void doInBackground(Void... voids) {
try {
InetAddress serverAddr = InetAddress.getByName(mHostIP);
Socket soc = new Socket(serverAddr,9999);
OutputStream toServer = soc.getOutputStream();
PrintWriter output = new PrintWriter(toServer);
output.println(mCommand);
DataOutputStream out = new DataOutputStream(toServer);
out.writeBytes(mCommand);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
It gets stuck at new Socket and throws exception after a while.
Here is the code for Python server:
import socket
import os
hostname = socket.gethostname()
IPAddr = socket.gethostbyname(hostname)
print('My IP: '+IPAddr)
port = 9999
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ("socket successfully created")
server_address = ('192.168.10.4', 9999)
s.bind(server_address)
s.listen(1)
print ("socket is listening")
while True:
try:
c, addr = s.accept()
print ('Got connection from', addr)
type = c.recv(1024).decode('utf-8')
print(type)
finally:
print('Could not connect')
c.close()
break
Have a close look at your firewall.
Hi I'm trying to send data from android client to a Python server on my PC, here is the code I don't really know what I'm doing wrong, (I'm not sure I understood how tcp sockets work on Javascript), I'm new to coding, I run this program when my mobile is connected to PC with USB.
Javascript Client:
package com.example.app;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.widget.Toast;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
public class MainActivity extends AppCompatActivity {
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = findViewById(R.id.idBtn);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"should do something",Toast.LENGTH_SHORT).show();
BackgroundTask b = new BackgroundTask();
b.execute();
}
});
}
class BackgroundTask extends AsyncTask<String,Void,String>
{
Socket s;
DataOutputStream dos;
String message;
#Override
protected String doInBackground(String... strings) {
message = "Hello_Javascript";
try {
InetAddress serverAddr = InetAddress.getByName("192.168.1.7");
s = new Socket(serverAddr, 10000);
dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(message);
dos.close();
}catch(IOException e){
e.printStackTrace();
}
return null;
}
}
}
Python Server (should be ok since I can communicate with another Python Client)
import socket
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = ('localhost', 10000)
print('starting up port ', server_address)
sock.bind(server_address)
# Listen for incoming connections
sock.listen(1)
while True:
# Wait for a connection
print('waiting for a connection')
connection, client_address = sock.accept()
try:
print('connection from ', client_address)
# Receive the data in small chunks and retransmit it
data = connection.recv(100)
print('received ', data)
finally:
# Clean up the connection
connection.close()
Thank you in advance!
You can use emulator to check if it works.Because both share same server this way
I'm making a Swift iOS application for my phone. It needs to connect to a python socket server. The server works fine when I do telnet using terminal on my mac, but when ever I try to connect using the app, the app returns UnknownError. But when I put in, for example www.google.com and port 80 or when I do a device on the local network with a webpage, it works fine. Why isn't it connecting and how can I fix it?
Here is a link to the library that I used: https://github.com/swiftsocket/SwiftSocket
Here is the code that is used on the device:
let host = "192.168.0.24"
let port = 250
var client: TCPClient?
client = TCPClient(address: host, port: Int32(port))
guard let client = client else { return }
switch client.connect(timeout: 10) {
case .success:
appendToTextField(string: "Connected to host \(client.address)")
if let response = sendRequest(string: "01", using: client) {
appendToTextField(string: "Response: \(response)")
ideaLabel.text = readResponse(from: client)
}
case .failure(let error):
appendToTextField(string: String(describing: error))
}
Here is the server code:
import socket
import sqlite3
from random import randint
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 250)
print("Starting Server")
s.bind(server_address)
print("Waiting for client")
s.listen(1)
alive = True
while(alive == True):
connection, client_address = s.accept()
print(client_address)
try:
command = connection.recv(2)
if (command == "01"):
conn = sqlite3.connect('ideas.db')
c = conn.cursor()
file = open("maxID.txt", "r")
maxID = (int(file.read()) + 1)
ideaNumber = (randint(1,maxID),)
c.execute('SELECT * FROM ideas WHERE id=?', ideaNumber)
idea1 = c.fetchone()
idea = str(idea1)
conn.close()
idea = idea.translate(None, "1234567890'(),u")
#idea = idea.translate("u",".")
print("Your idea is:")
print(idea)
connection.send(str(idea))
finally:
connection.close()