class Program { static void Main(string[] args) { Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); serverSocket.Bind(new IPEndPoint(IPAddress.Parse("10.6.0.38"), 88)); serverSocket.Listen(19); serverSocket.BeginAccept(ClientAccept, serverSocket); Console.ReadLine(); } static byte[] buffer = new byte[1024]; static void ClientAccept(IAsyncResult ar) { Socket serverSocket = ar.AsyncState as Socket; Socket clientSocket = serverSocket.EndAccept(ar); clientSocket.Send(Encoding.UTF8.GetBytes("hellooo")); clientSocket.BeginReceive(buffer, 0, 1024, SocketFlags.None, ServerReceive, clientSocket); serverSocket.BeginAccept(ClientAccept, serverSocket); } static void ServerReceive(IAsyncResult ar) { Socket clientSOcket = ar.AsyncState as Socket; try { int len = clientSOcket.EndReceive(ar); if(len == 0) { clientSOcket.Close(); return; } Console.WriteLine(Encoding.UTF8.GetString(buffer, 0, len)); clientSOcket.BeginReceive(buffer, 0, 1024, SocketFlags.None, ServerReceive, clientSOcket); } catch (Exception e) { Console.WriteLine(e); clientSOcket.Close(); } Console.ReadLine(); } } 客户端 class Program { static void Main(string[] args) { byte[] buffer = new byte[1024]; Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); clientSocket.Connect(new IPEndPoint(IPAddress.Parse("10.6.0.38"), 88)); int len = clientSocket.Receive(buffer, 0, 1024, SocketFlags.None); Console.WriteLine(Encoding.UTF8.GetString(buffer, 0, len)); while (true) { string temp = Console.ReadLine(); if (temp == "c") { clientSocket.Close(); return; } byte[] tempByte = Encoding.UTF8.GetBytes(temp); clientSocket.Send(tempByte); } } }
,相关文章
- 利用C#进行Socket通信编程之二:一个实例
- PHP 使用 mcrypt 扩展中的 mcrypt_encrypt() 和 mcrypt_decrypt() 对数据进行加密和解密
- 使用Jquery+EasyUI进行框架项目开发案例解说之中的一个---员工管理源代码分享
- Socket网络通讯开发总结之:Java 与 C进行Socket通讯 + [备忘] Java和C之间的通讯
- 按命令使用c#。net进行拨号呼叫。
- 使用栈Stack对整数数值的运算表达式字符串进行运算C#
- 使用C#在pictureBox中的图像中添加或减去颜色
- 在C#中使用类库中的SQL Server数据库文件
- 使用asp.net和C#在Web应用程序中进行逐页文本呈现
- 使用swift 3中的UISearchBar / UISearchController进行即时搜索