0
我有TCPServer.java:這種TCP交互有什麼問題?
import java.util.*;
import java.net.*;
import java.io.*;
public class TCPServer {
public static void main(String[] args) throws IOException {
ServerSocket tcp = new ServerSocket(1387);
while (true) {
Socket request = tcp.accept();
Scanner sc = new Scanner(request.getInputStream());
DataOutputStream out = new DataOutputStream(request.getOutputStream());
System.out.println("Request count: " + sc.nextLine());
out.writeBytes("send another request please");
}
}
}
和pythonClient.py
:
#!/usr/bin/python
import socket, time, sys
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((sys.argv[1], 1387))
count = 0
while True:
count += 1
sock.sendall(str(count) + "\n")
time.sleep(1)
data = sock.recv(1024)
print "received:\n", str(data)
我在同一主機上同時運行,並能接收「請求計數:X」每一秒都用遞增的x
TCPServer的控制檯中的值和
received:
send another request please
運行py的終端每秒thonClient.py。不過,我得到的只是在java控制檯中的「Request count:1」,沒有其他的東西。在終端,我得到:
received:
s
received:
end another request please
爲什麼這不按預期工作?爲什麼在一次迭代後全部被鎖定,爲什麼服務器的第一個響應被接受爲兩個不同的消息?