Python recv() doesn't wait for client response - python

I'm trying to set up a communication via socket between a PHP page (client) and a Python script (server). The PHP page has a button that, when clicked, sends "next" to the server. This part works but the problem happens when I refresh the page. In this situation I'm not writing anything to the server, yet, the function recv() of my server seems to receive something (an empty string) because the next lines are executed. Can someone tell me what's going on ?
client.php
<?php
$host = '127.0.0.1';
$port = 5353;
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die('Could not create socket\n');
$result = socket_connect($socket, $host, $port) or die('Could not connect to server\n');
if(isset($_POST['btnNext'])) {
$msg_to_server = 'next';
socket_write($socket, $msg_to_server, strlen($msg_to_server)) or die('Could not send data to server\n');
$msg_from_server = socket_read($socket, 1024) or die('Could not read server response\n');
echo 'Server said : ' . $msg_from_server;
}
?>
<form action='' method='POST' >
<button name='btnNext' type='submit'>Next</button>
</form>
server.py
import socket
host = '127.0.0.1'
port = 5353
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((host, port))
server_socket.listen(5)
while True:
client_socket, addr = server_socket.accept()
# doesn't wait for the client response :
msg_from_client = client_socket.recv(5000).decode()
print('Client said : ' + msg_from_client)

change your php part to this.
<?php
$host = '127.0.0.1';
$port = 5357;
if(isset($_POST['btnNext'])) {
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die('Could not create socket\n');
$result = socket_connect($socket, $host, $port) or die('Could not connect to server\n');
//creating socket connection under condition o.w making those empty str
$msg_to_server = 'next';
socket_write($socket, $msg_to_server, strlen($msg_to_server)) or die('Could not send data to server\n');
$msg_from_server = socket_read($socket, 1024) or die('Could not read server response\n');
echo 'Server said : ' . $msg_from_server;
socket_close($socket); //probably ?
}
?>

Related

How to stop C# from buffering the data it sends through socket?

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?

How to receive input from python socket server in android studio?

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();
}

Socket server between Unity and Raspberry doesn't connect

So I am trying to send data from the raspberry pi to unity.
I trying to create socket server to do so.
I can get the socket server running on the raspberry pi and can also look at the port with netstat -tulpn | grep :5005 in the terminal on the machine where the python script is running.
I also tried it on my mac and it also showed up as a TCP-server.
However when I try to connect to the same port and ip via Unity or on another machine it doesn't work. I also can't seem to find the port when listing all of the ports with netstat.
Unity spits out a "Connection refused" error.
Here is the code in Unity in C#
using UnityEngine;
using System.Collections;
using System;
using System.IO;
using System.Net.Sockets;
public class ClientSocket : MonoBehaviour
{
bool socketReady = false;
TcpClient mySocket;
public NetworkStream theStream;
StreamWriter theWriter;
StreamReader theReader;
public String Host = "192.168.8.137";
public Int32 Port = 5005;
void Start()
{
setupSocket();
TextMessage("SocketTest");
}
public void setupSocket()
{ // Socket setup here
try
{
mySocket = new TcpClient(Host, Port);
theStream = mySocket.GetStream();
theWriter = new StreamWriter(theStream);
theReader = new StreamReader(theStream);
socketReady = true;
}
catch (Exception e)
{
Debug.Log("Socket error:" + e); // catch any exceptions
}
}
public void TextMessage(string message)
{
if (socketReady == true)
{
theWriter.Write(message);
theWriter.Flush();
}
}
}
here is the code in python, which should be running on the raspberry pi.
import socket
import sys
backlog = 1
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('192.168.8.137', 5005))
s.listen(1)
try:
print ("is waiting")
client, address = s.accept()
while 1:
data = client.recv(size)
if data:
print (data)
finally:
print("closing socket")
cient.close()
s.close()
I'm new to socket servers, but I really trying to accomplish a connection here.
Thanks for reading!
am pretty sure you need to encode the data that you about to send in c# TcpClient
adding an example from my final project:
string data = "Hello Server!"; //the message in string (important it will be string)
byte[] msg = Encoding.Unicode.GetBytes(data); //encoded the message using unicode (utf-16)
NetworkStream stream = client.GetStream(); //get the tcp client stream
stream.Write(msg, 0, msg.Length); //write the message to the stream
and in the server you suppose to have something like that:
msg = clnt.recv(1024) #reciving the data
msg = msg.decode("utf-16") #decoding the data
print(msg) #printing the data
and i think thats it
and i would recommend using port above 10000 because most of the ports can be used

Why does my TCP connection not provide a response to a message when it works OK in netcat (nc) and telnet?

I am trying to send a message to a socket and read the response back in either PHP or Python. I have tried Telneting into the IP/Port and manually sending a command/receiving a response to verify the server is operating as expected. I have also tried connecting using nc (netcat) and that also works fine. In both cases I get a response immediately after sending a test string.
When I try to code it, I am seemingly able to successfully open a socket and send a message, but there is never a response after sending the test message. I've tried coding it in PHP & Python and the result is the same - nothing seems to be waiting to be read back from the socket. The read just times out with a blank response.
This is an example of what I do with nc to test the connection:
$ nc 192.168.85.251 10001
tC <--- I type this, and press enter.
tRIN. <--- this is the response
Here's the Python code I've been using:
#!/usr/bin/env python3
import socket
HOST = '192.168.85.251' # The server's hostname or IP address
PORT = 10001 # The port used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(b'tC\r')
data = s.recv(1024)
print('Received', repr(data))
Here's the equivalent PHP:
<?php
$host="192.168.85.251";
$port = 10001;
$payload = "tC" . Chr(10);
$fp = fsockopen ($host, $port, $errno, $errstr);
if (!$fp){
$result = "Error: could not open socket connection";
}
else {
// write the user string to the socket
fputs ($fp, $payload);
socket_set_timeout($fp, 5);
$feedback = fgets ($fp, 2);
echo "Returned: ". $feedback . " END\n";
}
?>
Can anyone suggest where I might be going wrong?
s.sendall(b'tC\r')
This is not what is done with telnet or nc. With these tools either b'tC\n' or b'tC\r\n' is send but not b'tC\r'. Likely the server does not respond since the expected message is not (fully) received.

How to connect android phone client to python server on same network using socket programming?

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.

Categories

Resources