2013-01-13 137 views
-1

所以我搜索了大约2周这个,我找不到任何合法的答案。不断侦听的套接字

我有两个项目,一个是服务器,另一个是客户端。

我只设法创建一个客户端控制台应用程序,只将数据发送到服务器,然后退出。没有其他的。

那么如何让客户端通过网络将文本框中的字符串发送到服务器,并且服务器可以持续监听。总是倾听。不仅仅是监听一次并完成程序,而是等待连接,当连接建立时,服务器接受客户端的字符串,写入字符串或写入文本框,然后立即返回监听连接。

我正在使用Windows窗体应用程序,所以我不想要一个控制台应用程序示例。

你可以使用的TcpClient和的TcpListener ...

+0

一个建议是使用'BeginReceive'和[Socket](http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.aspx)类上的'EndReceive'。然后在回调处理程序中再次调用'BeginReceive'。 –

回答

2

我不喜欢这样写道:

void Loop() 
{ 
    TcpListener l = new TcpListener(IPAddress.Any, Port); 
    WaitHandle[] h = new WaitHandle[2]; 
    h[0] = StopEvent; 

    WriteInfo("Listening on port {0}", Port); 

    l.Start(); 
    while (true) 
    { 
     var r = l.BeginAcceptTcpClient(null, null); 
     h[1] = r.AsyncWaitHandle; 
     // Wait for next client to connect or StopEvent 
     int w = WaitHandle.WaitAny(h); 
     if (w == 0) // StopEvent was set (from outside), terminate loop 
      break; 
     if (w == 1) 
     { 
      TcpClient c = l.EndAcceptTcpClient(r); 

      c.ReceiveTimeout = 90000; 
      c.SendTimeout = 90000; 

      // client is connected, spawn thread for it and continue to wait for others 
      var t = new Thread(ServeClient); 
      t.IsBackground = true; 
      t.Start(c); 
     } 
    } 
    l.Stop(); 

    WriteInfo("Listener stopped"); 
} 

其中Loop某处开始这样的:

StopEvent = new ManualResetEvent(false); 
    LoopThread = new Thread(Loop); 
    LoopThread.Start(); 

StopEvent用于终止听力循环。 ServeClient作为名称表示连接的客户端,看起来像这样:

void ServeClient(object State) 
    { 
     TcpClient c = (TcpClient)State; 

     NetworkStream s = c.GetStream(); 
     try 
     { 
      // Communicate with your client 
     } 
     finally 
     { 
      s.Close(); 
      c.Close(); 
     } 
    } 

这部作品在任何.NET应用程序(Windows服务,控制台,WPF或WinForms的)

+0

使用异步tcp客户机/服务器还有另一种可能性,我认为它更舒适。同样对于线程:使用布尔变量来中止while循环。否则,你必须通过使用Thread.Abort()来强制退出它,这是一件坏事。 ;) 异步TCP客户端的好例子: http://robjdavey.wordpress.com/2011/07/29/improved-asynchronous-tcp-client-example/ – Neurodefekt

+0

是的,Neurodefekt,我希望看到一些解释在异步套接字和TCP。介意在这里分享一些例子? –

+0

只要设置了StopEvent,while循环就会正常终止。没有必要放弃它。可以使用类似的方法来终止此处未显示的客户端线程 – CubeSchrauber