我正在尝试实现一个 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();}
}
}
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")
从客户端到服务器的第一条消息正确传送,但从服务器到客户端的第二条消息没有正确传送。使用 telnet 我检查服务器发送消息,但客户端陷入死锁并且没有收到消息。
我不明白为什么。
Thanks
看来你的缩进在Python服务器中是关闭的,因为要发送的代码
返回给客户端的消息无法到达。
即使修复了缩进之后,您的服务器实现也不正确,因为msg
不是一个String
。你需要解码msg
如下所示。另外,您需要将消息的长度作为short
因为你正在使用DataInputStream#readUTF
在你的客户端:
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")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)