将 Java 服务器与 Python 客户端连接
Connecting a Java Server with a Python Client
事情是这样的,我有一个基本的 java 服务器,可以将它从它接收到的内容发回给客户端。客户端写在python。我能够建立第一个连接,因为服务器会向客户端发送一条确认连接的消息。但是当我想让客户端发送服务器时,什么都不做。不知道是客户端没有发送问题还是服务器没有接收问题
这是服务器的代码:
int portNumber = Integer.parseInt(args[0]);
try (
ServerSocket serverSocket = new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
PrintWriter outs =
new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
) {
String inputLine, outputLine;
outputLine = "Hello socket, I'm server";
outs.println(outputLine);
outs.println("I' connected");
while ((inputLine = in.readLine()) != null) {
outputLine = inputLine;
outs.println(outputLine);
if (outputLine.equals("Bye."))
break;
}
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
}
} }
这是客户:
import socket
HOST = "localhost"
PORT = 8080
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST, PORT))
print (socket.getaddrinfo(HOST,PORT))
buffer_size = 100
while True :
data = sock.recv(buffer_size)
print ('you recieved :' , data)
test = input('send here\n')
sock.sendall(bytes(test, 'utf-8'))
print ('you sent : ' , test)
在 Python 客户端中:
您的提示包含 \n
但输入的结果没有?尝试在发送前将 \n
添加到 test
。
事情是这样的,我有一个基本的 java 服务器,可以将它从它接收到的内容发回给客户端。客户端写在python。我能够建立第一个连接,因为服务器会向客户端发送一条确认连接的消息。但是当我想让客户端发送服务器时,什么都不做。不知道是客户端没有发送问题还是服务器没有接收问题
这是服务器的代码:
int portNumber = Integer.parseInt(args[0]);
try (
ServerSocket serverSocket = new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
PrintWriter outs =
new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
) {
String inputLine, outputLine;
outputLine = "Hello socket, I'm server";
outs.println(outputLine);
outs.println("I' connected");
while ((inputLine = in.readLine()) != null) {
outputLine = inputLine;
outs.println(outputLine);
if (outputLine.equals("Bye."))
break;
}
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
}
} }
这是客户:
import socket
HOST = "localhost"
PORT = 8080
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST, PORT))
print (socket.getaddrinfo(HOST,PORT))
buffer_size = 100
while True :
data = sock.recv(buffer_size)
print ('you recieved :' , data)
test = input('send here\n')
sock.sendall(bytes(test, 'utf-8'))
print ('you sent : ' , test)
在 Python 客户端中:
您的提示包含 \n
但输入的结果没有?尝试在发送前将 \n
添加到 test
。