epa*_*olo 5 python java sockets client-server
我正在尝试实现Java-python客户端/服务器套接字。客户端使用Java,服务器使用python编写
Java客户端
import java.io.*;
import java.net.*;
import java.lang.*;
public class client {
public static void main(String[] args) {
try{
Socket socket=new Socket("localhost",2004);
DataOutputStream dout=new DataOutputStream(socket.getOutputStream());
DataInputStream din=new DataInputStream(socket.getInputStream());
dout.writeUTF("Hello");
dout.flush();
System.out.println("send first mess");
String str = din.readUTF();//in.readLine();
System.out.println("Message"+str);
dout.close();
din.close();
socket.close();
}
catch(Exception e){
e.printStackTrace();}
}
}
Run Code Online (Sandbox Code Playgroud)
Python服务器
import socket
soc = socket.socket()
host = "localhost"
port = 2004
soc.bind((host, port))
soc.listen(5)
while True:
conn, addr = soc.accept()
print ("Got connection from",addr)
msg = conn.recv(1024)
print (msg)
print(len(msg))
if "Hello"in msg:
conn.send("bye".encode('UTF-8'))
else:
print("no message")
Run Code Online (Sandbox Code Playgroud)
从客户端到服务器的第一条消息正确传递,但从服务器到客户端的第二条消息正确传递。我使用telnet来检查服务器是否发送了邮件,但是客户端陷入了僵局,没有收到邮件。我不明白为什么。
谢谢
似乎您的缩进在 Python 服务器中关闭,因为无法将消息发送回客户端的代码。
即使在修复缩进之后,您的服务器实现也不正确,因为msg不是String. 您需要msg按如下所示进行解码。此外,short由于您DataInputStream#readUTF在客户端中使用,您需要将消息的长度作为 a 发送:
import socket
soc = socket.socket()
host = "localhost"
port = 2004
soc.bind((host, port))
soc.listen(5)
while True:
conn, addr = soc.accept()
print("Got connection from",addr)
length_of_message = int.from_bytes(conn.recv(2), byteorder='big')
msg = conn.recv(length_of_message).decode("UTF-8")
print(msg)
print(length_of_message)
# Note the corrected indentation below
if "Hello"in msg:
message_to_send = "bye".encode("UTF-8")
conn.send(len(message_to_send).to_bytes(2, byteorder='big'))
conn.send(message_to_send)
else:
print("no message")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1959 次 |
| 最近记录: |