我写了一个客户端和服务端,客户端只发送不接受,服务端只接受不发送,
客户端采用异步连接和异步发送,客户端每次发送都要新建连接,服务端采用异步接收连接和异步发送,
我想实现的是客户端新建一个连接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();
                    //异步接收连接
                    newsock.BeginAccept(new AsyncCallback(OnConnectRequest), newsock);
                    allDone.WaitOne();
                }
            }
            catch (Exception ex)
            {
                showClientMsg("连接错误:" + ex.Message);
            }
        public void OnConnectRequest(IAsyncResult ar)
        {
            try
            {
                allDone.Set();
                Socket listener = (Socket)ar.AsyncState;
                Socket handler = listener.EndAccept(ar);
                //异步接收数据
                handler.BeginReceive(result, 0, result.Length, 0, new AsyncCallback(ReadCallback), handler);
            }
            catch (Exception ex)
            {
                showClientMsg("接收数据错误:" + ex.Message);            }
        }
        public void ReadCallback(IAsyncResult ar)
        {
            try
            {
                Socket handler = (Socket)ar.AsyncState;
                int bytesRead = handler.EndReceive(ar);
                {
                    string stringdata = Encoding.ASCII.GetString(result, 0, bytesRead);
                    string ip = handler.RemoteEndPoint.ToString();
                    //反序列化
                    MemoryStream ms = new MemoryStream(result);
                    //移动到头部
                    ms.Position = 0;
                    BinaryFormatter formatter = new BinaryFormatter();
                    Model.UploadEntities.AllEntities enti = formatter.Deserialize(ms) as Model.UploadEntities.AllEntities;
                    DateTimeOffset now = DateTimeOffset.Now;                    //显示客户端发送过来的信息
                    if (enti.MyCheckLevelData != null)
                    {
                        showClientMsg(ip + "    油罐名称:" + enti.MyCheckLevelData.StorehouseName + "   液位:" + enti.MyCheckLevelData.Leval.ToString() + "\r\n");
                    }
                    else if (enti.MyCheckFlowData != null)
                    {
                        showClientMsg(ip + "    油罐名称:" + enti.MyCheckFlowData.StorehouseName + "   流量:" + enti.MyCheckFlowData.Flow.ToString() + "\r\n");
                    }
                    else if (enti.MyCheckTData != null)
                    {
                        showClientMsg(ip + "    油罐名称:" + enti.MyCheckTData.StorehouseName + "   平均温:" + enti.MyCheckTData.AT.ToString() + "\r\n");
                    }
     //上面等于说是服务端接收到数据了,然后我想在这里关闭socket,下面这两句话不知道能关闭么???求大神知道啊!!!
                    handler.Shutdown(SocketShutdown.Both);
                    handler.Close();
                }            }
            catch (Exception ex)
            {
                showClientMsg("错误:" + ex.Message);
            }
        }
socketasynchronous通信多线程异步

解决方案 »

  1.   

    我在网上搜的那些怎么看着都好像没有主动关闭socket的呢?如果不管服务器不是很浪费资源么???跪求解惑啊!!!
      

  2.   

     handler.Shutdown(SocketShutdown.Both);
     handler.Close();
    这两句话真的能关闭么?我就怕没关闭,客户端的端口一直在随机增加
      

  3.   

    你Socket对象的操作跟异步与否没关系的,一个引用类型你不管怎么传递来传递去,操作的还是建立连接的那个Socket,Socket.Close()后就会关闭那个连接。
      

  4.   


    哦,好的,还有一个问题想请教下,就是客户端connect的时候系统是随机分配一个端口的,那我把这个socket关掉后,客户端的这个端口还能再次利用么?因为我发送的频率挺高的,会不会把随机的端口用完啊。
      

  5.   


    哦,好的,还有一个问题想请教下,就是客户端connect的时候系统是随机分配一个端口的,那我把这个socket关掉后,客户端的这个端口还能再次利用么?因为我发送的频率挺高的,会不会把随机的端口用完啊。
     不会
      

  6.   

    服务器端程序 using System; 
    using System.Net; 
    using System.Net.Sockets; 
    using System.Text; 
    namespace SocketServer 

    /// <summary> 
    /// Class1 的摘要说明。 
    /// </summary> 
    class Class1 

      /// <summary> 
      /// 应用程序的主入口点。 
      /// </summary> 
      //定义端口号 
      private const int porNum=81; 
      [STAThread] 
      static void Main(string[] args) 
      { 
       // 
       // TODO: 在此处添加代码以启动应用程序 
       // 
       bool done=false; 
       TcpListener listener=new TcpListener(porNum); 
       listener.Start(); 
       while(!done){ 
       Console.Write("正在侦听81端口..."); 
        TcpClient client=listener.AcceptTcpClient(); 
        Console.WriteLine("\n处理连接请求..."); 
        NetworkStream ns=client.GetStream(); 
        //ns.Read(,0,); 
        byte[] bytes=new byte[1024]; 
        int bytesRead=ns.Read(bytes,0,bytes.Length); 
        Console.WriteLine(Encoding.BigEndianUnicode.GetString(bytes,0,bytesRead)); 
        byte[] byteTime=Encoding.ASCII.GetBytes(DateTime.Now.ToString()); 
        try 
        { 
         ns.Write(byteTime,0,byteTime.Length); 
         ns.Close(); 
         client.Close(); 
        } 
        catch(Exception ex){ 
        Console.WriteLine(ex.ToString()); 
        } 
       } 
       listener.Stop(); 
      } 

    } Web客户端 添加命名空间: 
    using System.Net; 
    using System.Net.Sockets; 
    using System.Text; 连接代码: 
    private void socketButton_Click(object sender, System.EventArgs e) 
      {//连接服务器程式 
       try 
       { 
        //开始连接 
        TcpClient client=new TcpClient("192.168.0.100",81); 
        NetworkStream ns=client.GetStream(); 
        byte[] byteTime=Encoding.BigEndianUnicode.GetBytes("客户端数据提交\n"); 
        ns.Write(byteTime,0,byteTime.Length); 
        //返回客户端信息 
        byte[] clientIp=Encoding.BigEndianUnicode.GetBytes("客户端IP地址:"+Request.UserHostAddress+"\n"); 
        ns.Write(clientIp,0,clientIp.Length); 
        byte[] bytes=new byte[1024]; 
        int bytesRead=ns.Read(bytes,0,bytes.Length); 
        showLabel.Text="服务器返回信息"+Encoding.ASCII.GetString(bytes,0,bytesRead); 
        client.Close(); 
       } 
       catch(Exception ex) 
       { 
        showLabel.Text="抛出异常"+ex.ToString(); 
       } 
       finally{} 
      }
    参考!