【发布时间】:2021-08-11 01:01:57
【问题描述】:
我正在创建一个工作起来有点像聊天室的异步 TCP 服务器,或者至少应该这样。当一个新客户端连接到服务器时,他会收到一条欢迎消息,并且每次他发送一条消息时,服务器都会回显它。当只有一个客户端连接时它工作得很好,但是当另一个客户端连接时,他没有收到欢迎消息,也没有回显。
这是我的一些代码。
private void btn_startserver_Click(object sender, EventArgs e)
{
server = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp); //Populates the Server obj.
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 23);
server.Bind(iep);
server.Listen(5);
server.BeginAccept(new AsyncCallback(AcceptConn), server);
WriteOnLog("Waiting for incoming connections...");
Thread t1 = new Thread(() => verifyCon(server));
t1.Start();
}
public void AcceptConn(IAsyncResult iar)
{
Socket oldserver = (Socket)iar.AsyncState;
Socket client = oldserver.EndAccept(iar);
clientList.Add(client);
WriteOnLog("Connected to: " + client.RemoteEndPoint.ToString());
string stringData = "Connected Successfully\r\nWelcome to the Server\r\n";
byte[] message1 = Encoding.UTF8.GetBytes(stringData);
client.BeginSend(message1, 0, message1.Length, SocketFlags.None,
new AsyncCallback(SendData), client);
WriteOnClients(client.RemoteEndPoint.ToString(), "add");
}
void SendData(IAsyncResult iar)
{
Socket client = (Socket)iar.AsyncState;
int sent = client.EndSend(iar);
client.BeginReceive(data, 0, size, SocketFlags.None,
new AsyncCallback(ReceiveData), client);
}
void ReceiveData(IAsyncResult iar)
{
Socket client = (Socket)iar.AsyncState;
string curClient = client.RemoteEndPoint.ToString();
int recv = client.EndReceive(iar);
if (recv == 0)
{
client.Close();
WriteOnLog("Connection lost with " + curClient);
WriteOnClients(curClient, "remove");
WriteOnLog("Waiting for client...");
connectedClients.Remove(curClient);
server.BeginAccept(new AsyncCallback(AcceptConn), server);
return;
}
string receivedData = Encoding.ASCII.GetString(data, 0, recv);
WriteOnLog(receivedData);
byte[] message2 = Encoding.UTF8.GetBytes(receivedData);
client.BeginSend(message2, 0, message2.Length, SocketFlags.None,
new AsyncCallback(SendData), client);
}
【问题讨论】:
-
与当前问题无关,但请选择一种编码并始终如一地使用它。如果不是现在,那么混合 ASCII 和 UTF8 看起来就像是混乱的秘诀。
-
另外,请注意,如果您想要 messages,则由 you 实施某种识别它们的方法。 不保证客户端对
Send的每次调用都将与服务器对Receive的单个调用相匹配(反之亦然)。 TCP 是一个连续的字节流。 -
感谢您的提示!我抓住了一些代码,但还没有完成将其修改为 UTF8。哦,我会看到有关识别消息的信息!试着想办法……谢谢!!!
标签: c# asynchronous tcp