gpt4 book ai didi

Java客户端Python服务器端socket编程

转载 作者:行者123 更新时间:2023-12-01 12:36:48 25 4
gpt4 key购买 nike

我有一个 java 客户端程序,它向 python 服务器发送一条消息“Hello”。

Java代码

    import java.io.*;  
import java.net.*;
public class MyClient {
public static void main(String[] args) {

try{
Socket soc=new Socket("localhost",2004);
DataOutputStream dout=new DataOutputStream(soc.getOutputStream());
dout.writeUTF("Hello");
dout.flush();
dout.close();
soc.close();
}catch(Exception e){
e.printStackTrace();}
}

Python服务器代码

    import socket               # Import socket module

soc = socket.socket() # Create a socket object
host = "localhost" # Get local machine name
port = 2004 # Reserve a port for your service.
soc.bind((host, port)) # Bind to the port
soc.listen(5) # Now wait for client connection.
while True:
conn, addr = soc.accept() # Establish connection with client.
print ("Got connection from",addr)
msg = conn.recv(1024)
print (msg)
if ( msg == "Hello Server" ):
print("Hii everyone")
else:
print("Go away")

问题是 java 客户端能够向 python 服务器发送 Hello 消息,但在 python 端 else 语句始终执行并输出“Goaway”。python 版本 2.7

输出:

('Got connection from', ('127.0.0.1', 25214))
Hello
Go away

最佳答案

您收到客户的“你好”。

if ( msg == "Hello" ):
print("Hii everyone")
else:
print("Go away")

关于Java客户端Python服务器端socket编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25505725/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com