使用c#async从服务器发送数据

时间:2015-05-18 03:54:20

标签: c#-4.0 asyncsocket

我指的是.net asyn示例 https://msdn.microsoft.com/en-us/library/system.net.sockets.socketasynceventargs.aspx

此代码服务器在收到消息时响应客户端。我的问题

1)服务器如何将数据发送到所需的客户端,我是否需要找到在连接期间启动的相同SocketAsyncEventArgs并发送它?

2)服务器如何同时从同一客户端接收?我的意思是我可以同时发送和接收内容。

谢谢

1 个答案:

答案 0 :(得分:0)

public void startServer(int port)
{
    port1 = port;//sets the port number
    th = new Thread(thServ);//creates user thread
    UserCounter = new Thread(nextUser1);//creates token thread
    UserCounter.Start();
    th.Start();
}//end start server 

public void thServ()
{
    TcpClient clientSocket = default(TcpClient);//Setup The Client socket type
    try
    {
        //MessageBox.Show(port1.ToString());
        serverSocket = new TcpListener(port1); 
        serverSocket.Start();//start server

    }
    catch { MessageBox.Show("Port is not available"); return; }


    Boolean isthere = true; 
    while (isthere)//start listening for client... would set boolean for back ground worker?
    {
        try
        {
            //countMe++;
            //MessageBox.Show("Server has started");
            //MessageBox.Show(SampleInv.Form4.setUp());//test passing info of user data
            clientSocket = serverSocket.AcceptTcpClient(); // accept client
            //MessageBox.Show("user is here0");
            handleClinet client = new handleClinet();// creat instance of handle client

            client.startClient(clientSocket);//dowork for client

        }
        catch  { isthere = false; MessageBox.Show("clientSocket Failed"); }
    }// end while (shouldn't this be in a try catch)

}//end thServ