知识大全 c#(Socket)同步套接字代码示例

Posted

篇首语:倘若心中愿意,道路千千条。倘若心中不愿意,理由万万个。本文由小常识网(cha138.com)小编为大家整理,主要介绍了知识大全 c#(Socket)同步套接字代码示例相关的知识,希望对你有一定的参考价值。

c#(Socket)同步套接字代码示例  以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧!

  同步客户端套接字示例    下面的示例程序创建一个连接到服务器的客户端 该客户端是用同步套接字生成的 因此挂起客户端应用程序的执行 直到服务器返回响应为止 该应用程序将字符串发送到服务器 然后在控制台显示该服务器返回的字符串     C#    using System;    using System Net;    using System Net Sockets;    using System Text;    public class SynchronousSocketClient     public static void StartClient()     // Data buffer for ining data     byte[] bytes = new byte[ ];    // Connect to a remote device     try     // Establish the remote endpoint for the socket     // This example uses port on the local puter     IPHostEntry ipHostInfo = Dns Resolve(Dns GetHostName())    IPAddress ipAddress = ipHostInfo AddressList[ ];    IPEndPoint remoteEP = new IPEndPoint(ipAddress );    // Create a TCP/IP  socket     Socket sender = new Socket(AddressFamily InterNeork     SocketType Stream ProtocolType Tcp );    // Connect the socket to the remote endpoint Catch any errors     try     sender Connect(remoteEP);    Console WriteLine( Socket connected to     sender RemoteEndPoint ToString());    // Encode the data string into a byte array     byte[] msg = Encoding ASCII GetBytes( This is a test<EOF> );    // Send the data through the socket     int bytesSent = sender Send(msg);    // Receive the response from the remote device     int bytesRec = sender Receive(bytes);    Console WriteLine( Echoed test =     Encoding ASCII GetString(bytes bytesRec));    // Release the socket     sender Shutdown(SocketShutdown Both);    sender Close();    catch (ArgumentNullException ane)     Console WriteLine( ArgumentNullException : ane ToString());    catch (SocketException se)     Console WriteLine( SocketException : se ToString());    catch (Exception e)     Console WriteLine( Unexpected exception : e ToString());        catch (Exception e)     Console WriteLine( e ToString());            public static int Main(String[] args)     StartClient();    return ;            同步服务器套接字示例 下面的示例程序创建一个接收来自客户端的连接请求的服务器 该服务器是用同步套接字生成的     因此在等待来自客户端的连接时挂起服务器应用程序的执行 该应用程序接收来自客户端的字符串     在控制台显示该字符串 然后将该字符串回显到客户端 来自客户端的字符串必须包含字符串 <EOF>     以发出表示消息结尾的信号

cha138/Article/program/net/201311/12914

相关参考