I'm creating an async TCP Server that works kinda like a chat room, or at least it should. When a new client connects to the server he receives a welcome message and also everytime he sends a message, the server echos it back. It works well when only one client is connected, but when another one connects, he doesn't receive the welcome msg nor the echos.
Here's some of my code.
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);
}
After you handle the first incoming connection (EndAccept
), you need to call BeginAccept
again to accept the next connection.
Currently you call BeginAccept
only during initialization, and when a client disconnects.