我在Python中创建了一个套接字服务器,在C#中创建了一个套接字客户端。无论何时在客户端发生事件,它都会向服务器发送一个字符串,其中包含时间信息(hh:mm:ss:ffff)以及负整数或正整数,并打印出字符串。
问题是服务器有时会在同一行中同时打印出多个事件信息。例如:
//C# CLIENT OUTPUT
05:42:16:5942,-8
05:42:16:5962,+1
05:42:16:5972,+1
05:42:16:5992,-1
05:42:16:6002,-1
05:42:16:6023,-1
05:42:16:6043,-1
05:42:16:7856,-7
#Python SERVER OUTPUT
05:42:16:5942,-8
05:42:16:5962,+1
05:42:16:5972,+105:42:16:5992,-1 <- the error
05:42:16:6002,-1
05:42:16:6023,-1
05:42:16:6043,-1
05:42:16:7856,-7
我不知道导致问题的原因。这是'服务器和客户端的来源。
#SERVER.py
from socket import *
serverSocket = socket(AF_INET,SOCK_STREAM)
serverSocket.bind(('localhost',999))
serverSocket.listen(1)
connectionSocket, addr = serverSocket.accept()
i = 0
sentence = ""
while True:
sentence = connectionSocket.recv(1024)
sentence = sentence.decode("UTF-8","ignore")
if sentence != "end":
print(sentence)
else:
print(sentence)
connectionSocket.close()
print("CLOSED")
break
//CLIENT.cs
string sendingValue;
static Socket sck;
sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 999);
sck.Connect(localEndPoint);
// The below runs whenever an event occurs
string t = DateTime.Now.ToString("hh:mm:ss:ffff");
string userCount = GetUserRealCount().Trim();
sendingValue = t + "," + userCount;
byte[] data = System.Text.Encoding.ASCII.GetBytes(sendingValue);
sck.Send(data);