同步服务器套接字挂起应用程序的执行,直到套接字上接收到连接请求。同步服务器套接字不适用于在操作中大量使用网络的应用程序,但它们可能适用于简单的网络应用程序。
使用 Bind 和 Listen 方法设置 Socket 以在终结点上侦听之后,Socket 就可以随时使用 Accept 方法接受传入的连接请求了。应用程序被挂起,直到调用 Accept 方法时接收到连接请求。
接收到连接请求时,Accept 返回一个与连接客户端关联的新 Socket 实例。下面的示例读取客户端数据,在控制台上显示该数据,然后将该数据回显到客户端。Socket 不指定任何消息协议,因此字符串“<EOF>”标记消息数据的结尾。它假定一个名为 listener 的 Socket 已初始化,并绑定到一个终结点。
Console.WriteLine("Waiting for a connection...") Dim handler As Socket = listener.Accept() Dim data As String = Nothing While True bytes = New Byte(1024) {} Dim bytesRec As Integer = handler.Receive(bytes) data += Encoding.ASCII.GetString(bytes, 0, bytesRec) If data.IndexOf("<EOF>") > - 1 Then Exit While End If End While Console.WriteLine("Text received : {0}", data) Dim msg As Byte() = Encoding.ASCII.GetBytes(data) handler.Send(msg) handler.Shutdown(SocketShutdown.Both) handler.Close()
Console.WriteLine("Waiting for a connection..."); Socket handler = listener.Accept(); String data = null; while (true) { bytes = new byte[1024]; int bytesRec = handler.Receive(bytes); data += Encoding.ASCII.GetString(bytes,0,bytesRec); if (data.IndexOf("<EOF>") > -1) { break; } } Console.WriteLine( "Text received : {0}", data); byte[] msg = Encoding.ASCII.GetBytes(data); handler.Send(msg); handler.Shutdown(SocketShutdown.Both); handler.Close();




位访问者
当前在线人数
人
页面执行:31.25毫秒