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();
}
Related
I have been trying to send data through C# to Python using socket.
I tried to program the sender using Python to make sure everything is set up properly using the Python code be
import socket
import sys
HEADERSIZE = 10
raw_msg = "a"
print(f"{len(raw_msg):<{HEADERSIZE}}"+raw_msg)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((socket.gethostname(), 1235))
s.listen(5)
clientsocket, address = s.accept()
print(f"Connection from {address} has been established.")
while True:
raw_msg = input("input: ")
msg = f"{len(raw_msg):<{HEADERSIZE}}"+raw_msg
clientsocket.send(bytes(msg,"utf-8"))
if raw_msg == "bye":
break
s.detach()
s.close()
When the code is executed, the packages sent look like:
b'39 readEx'
b'cel|x,test_Purch'
b'ase_Forecast.xls'
b'x'
b'45 printD'
b'ataFrames|x,test'
b'_Purchase_Foreca'
b'st.xlsx'
So, I did it using C# using the code below:
class Connection
{
int ServerPortNum;
Socket connectionSocket;
Socket welcomingSocket;
public Connection() {
ServerPortNum = 1235;
IPEndPoint serverEndPoint = new System.Net.IPEndPoint(IPAddress.Loopback,ServerPortNum);
welcomingSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
welcomingSocket.NoDelay = true;
Console.WriteLine("Starting");
welcomingSocket.Bind(serverEndPoint);
welcomingSocket.Listen(5);
}
public void Accept() {
connectionSocket = welcomingSocket.Accept();
}
public void send(string raw_msg_string)
{
char[] lengthCharArray = raw_msg_string.Length.ToString().ToCharArray();
string whiteSpace = String.Concat(Enumerable.Repeat(" ", 10-lengthCharArray.Length));
string header = new string(lengthCharArray) + whiteSpace;
Console.WriteLine(header + raw_msg_string);
byte[] msg = Encoding.ASCII.GetBytes(header + raw_msg_string);
connectionSocket.Send(msg);
}
public void ShutDown() {
connectionSocket.LingerState = new LingerOption(false, 0);
connectionSocket.Shutdown(SocketShutdown.Both);
connectionSocket.Disconnect(false);
connectionSocket.Close();
}
}
However the problem is C# is buffering the data it sends which is causing problems for my application. So, the send code for the same input looks like this:
b'39 readEx'
b'cel|x,test_Purch'
b'ase_Forecast.xls'
b'x45 print'
b'DataFrames|x,tes'
b't_Purchase_Forec'
b'ast.xlsx'
b''
So my question is, how can I prevent C# from buffering the data and cause it to send the package if the message is over instead of buffering it so that the packages look like the ones in python?
I have a program in python named server.py and I want to send multiple messages to client.cs using a socket, and use them while python program is still running.
I tried before in py (server) to py (client) and it works, but when I try py (server) to C# (client) I get multiple exceptions.
This is server.py:
import socket
import time
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port = 7634
s.bind((host, port))
s.listen(1)
con, addr = s.accept()
print("Connected with: ", addr)
message = 1800
while message <= 2000:
con.send(str(message).encode())
message += 1
time.sleep(0.1)
Client.py:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port = 7634
s.connect((host, port))
message = 1800
while message <= 2000:
message = int(s_messg.decode())
print(message, "\n")
As I said before this works fine
Sending 1800 and instantly receiving 1800
Sending 1801 and instantly receiving 1801
...
Sending 2000 and instantly receiving 2000
I saw C# client code from Microsoft doc, but as I said before I get multiple exceptions:
SocketException: System.Net.Internals.SocketExceptionFactory+ExtendedSocketException
It says that the connection could not be established.
try
{
server = "127.0.0.1";
Int32 port = 7634;
TcpClient client = new TcpClient(server, port);
NetworkStream stream = client.GetStream();
Byte []data = new Byte[256];
// String to store the response ASCII representation.
String responseData = String.Empty;
// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine("Received: {0}", responseData);
// Close everything.
stream.Close();
client.Close();
}
catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException: {0}", e);
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
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()
}
}
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.