我想建立一个服务器套接字并向客户端发送一条线,客户端将打印该线
但是当我打印从服务器套接字接收到的数据时,只打印文件的第一行,其他的都错过了
我注意到有时数据在“\n”之后仍然有数据所以我添加了以下两行代码,它会显示错误“找不到子字符串”但有时客户端会收到这种数据“5000\n1000”所以客户需要保留1000 ...
remain = data[data.index("\n")+1:]
data = remain
这是我要发送给客户的数据
1000 2000 3000 4000 5000
1000 3000 5000 7000 9000
1111 2222 3333 4444 5555
服务器
import socket
Input = open("./Data","r")
data = Input.read()
Input.close()
# Construct the server_socket
server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_sock.bind(('localhost',15000))
server_sock.listen(1)
(client_socket,address) = server_sock.accept()
# send data
for line in data:
client_socket.send(line)
client_socket.send("EOF")
client_socket.close()
server_sock.close()
客户
import socket
client_sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
client_sock.connect(('localhost',15000))
data = ""
while True:
part = client_sock.recv(100)
data = data + part
if "\n" in data or "EOF" in data:
list = data[:data.index("\n")].split(" ")
print(list)
remain = data[data.index("\n")+1:]
data = remain
if "EOF" in data:
break
client_sock.close()
result.close()