日期:2014-05-17  浏览次数:20683 次

关于socket异步通信
我写了一个客户端和服务端,客户端只发送不接受,服务端只接受不发送,
客户端采用异步连接和异步发送,客户端每次发送都要新建连接,服务端采用异步接收连接和异步发送,
我想实现的是客户端新建一个连接socket,发送过去消息,服务端接收到消息后就立即关闭此socket,
可是采用了异步后,怎么才能关闭socket呢
服务端代码

        //监听函数                 
        public void Listen()
        {
            //设置端口                          
            setPort = int.Parse(serverport.Text.Trim());
            //设置IP
            IPAddress ip = IPAddress.Parse(serverIP.Text.Trim());
            //初始化Socket实例                          
            newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //初始化终结点实例                          
            localEP = new IPEndPoint(ip, setPort);
            try
            {
                //绑定                                  
                newsock.Bind(localEP);
                //监听                                  
                newsock.Listen(50);//挂起连接队列的最大长度,根据操作系统而定

                //开始接受连接,异步。                                  
                //newsock.BeginAccept(new AsyncCallback(OnConnectRequest), newsock);
                while (true)
                {
                    allDone.Reset();