Python服务器和Java客户端套接字
python中的服务器Python服务器和Java客户端套接字,java,python,Java,Python,python中的服务器 import socket from sys import getsizeof host = '' port = 5560 storedValue = "Yo, what's up?" def setupServer(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print("Socket created.") try: s.bind((host, port)
import socket
from sys import getsizeof
host = ''
port = 5560
storedValue = "Yo, what's up?"
def setupServer():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Socket created.")
try:
s.bind((host, port))
except socket.error as msg:
print(msg)
print("Socket bind comPlete.")
return s
def setupConnection():
s.listen(1) # Allows one connection at a time.
print("Waiting for client")
conn, address = s.accept()
return conn
def GET():
reply = storedValue
return reply
def REPEAT(dataMessage):
reply = dataMessage[1]
return reply
def dataTransfer(conn, s):
# A big loop that sends/receives data until told not to.
while True:
# Receive the data
data = conn.recv(1028) # receive the data
data = data.decode('utf-8')
data = data.strip()
print("data value from client: " + data)
# Split the data such that you separate the command
# from the rest of the data.
command = str(data)
print("data length from client: " + command)
reply = ""
if command == "GET":
reply = GET()
print (command)
print (reply)
elif command == 'REPEAT':
reply = REPEAT(dataMessage)
elif command == 'EXIT':
print("Our client has left us :(")
break
elif command == 'KILL':
print("Our server is shutting down.")
s.close()
break
else:
reply = 'Unknown Command'
# Send the reply back to the client
conn.sendall(bytes(reply, 'utf-8'))
print("Data has been sent!")
conn.close()
s = setupServer()
while True:
try:
conn = setupConnection()
dataTransfer(conn, s)
except:
break
java中的客户端
import java.io.*;
import java.net.*;
import java.util.*;
public class pcClient {
public static void main(String[] args) {
Socket rpiSocket = null;
DataInputStream in = null;
PrintStream out = null;
try {
rpiSocket = new Socket("localhost",5560);
out = new PrintStream(rpiSocket.getOutputStream());
in = new DataInputStream(new BufferedInputStream(rpiSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: hostname");
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: hostname");
}
try {
if (rpiSocket != null && out != null && in != null) {
while(true) {
System.out.println("Please input your command ");
Scanner scanner = new Scanner(System.in);
String command = scanner.nextLine();
if(command.equals("KILL")) {
break;
}
System.out.println("Sending command to client: " + command);
out.println(command);
byte[] bytes = new byte[1024];
in.read(bytes);
String reply = new String(bytes, "UTF-8");
System.out.println("Reply from server: " + reply.trim());
}
}
rpiSocket.close();
System.out.println("Connections closed successfully");
}
catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
我有上面的python服务器和一个java客户端。java客户端从用户获取输入并将其发送到python。所有这些都运作良好。但是,python服务器正在从java服务器接收字符串和一个额外的空字符串。例如,在java客户端,当我发送单词“GET”时,python服务器能够接收这个GET并打印“Yo,怎么了?”。但是,它返回到“While True”,并立即另外接收一个空字符串,然后开始使用该空字符串检查条件。我试图修剪从java客户端接收到的字符串。我怎样才能解决这个问题?谢谢 conn.recv()
返回尽可能多的立即可用数据(例如一个数据包)。另一方面,Java运行时库可以自由地将发送的数据细分为多个数据包。我猜它发送一个带有“GET”的数据包和另一个带有最后换行符的数据包
一种解决方案是,服务器等待并从流中收集输入,直到找到一个换行符来完成命令。由于您从java程序中使用了
out.println(命令)
,所以出现了问题。它通过套接字发送命令和一些换行符。如果将其替换为out.print(命令)
,则问题将得到解决
println可能在两个调用中内部发送主字符串和换行符,我不确定。但理想情况下,客户端的每个“命令”都应该首先包含命令字符串的长度,然后才是真正的命令。如果recv返回的字节数大于或小于要求的字节数,服务器端可能需要缓冲或分割输入数据
有一个小的python库datachunkpy,它可以帮助拆分和处理命令()