c# socket初学小demo
2022/3/9 11:14:42
本文主要是介绍c# socket初学小demo,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
转载于:博主文章
1.客户端:
点击查看代码
static Socket ClientSocket; public void Send() { String IP = "127.0.0.1"; int port = 8885; IPAddress ip = IPAddress.Parse(IP); //将IP地址字符串转换成IPAddress实例 ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//使用指定的地址簇协议、套接字类型和通信协议 IPEndPoint endPoint = new IPEndPoint(ip, port); // 用指定的ip和端口号初始化IPEndPoint实例 ClientSocket.Connect(endPoint); //与远程主机建立连接 Console.WriteLine("开始发送消息"); string send=Console.ReadLine(); byte[] message = Encoding.UTF8.GetBytes(send); //通信时实际发送的是字节数组,所以要将发送消息转换字节 ClientSocket.Send(message); Console.WriteLine("发送消息为:" + send); byte[] receive = new byte[1024]; int length = ClientSocket.Receive(receive); // length 接收字节数组长度 Console.WriteLine("接收消息为:" + Encoding.UTF8.GetString(receive)); ClientSocket.Close(); //关闭连接 }
2.服务端
点击查看代码
static Socket ReceiveSocket; public void Receive() { int port = 8885; IPAddress ip = IPAddress.Any; // 侦听所有网络客户接口的客活动 ReceiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//使用指定的地址簇协议、套接字类型和通信协议 <br> //ReceiveSocket.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReuseAddress,true); //有关套接字设置 IPEndPoint endPoint = new IPEndPoint(ip, port); ReceiveSocket.Bind(new IPEndPoint(ip, port)); //绑定IP地址和端口号 ReceiveSocket.Listen(10); //设定最多有10个排队连接请求 Console.WriteLine("建立连接"); Socket socket = ReceiveSocket.Accept(); byte[] receive = new byte[1024]; socket.Receive(receive); Console.WriteLine("接收到消息:" + Encoding.UTF8.GetString(receive)); string test=Console.ReadLine(); byte[] send = Encoding.UTF8.GetBytes(test); socket.Send(send); //ASCII Console.WriteLine("发送消息为:" + Encoding.UTF8.GetString(send)); }
这篇关于c# socket初学小demo的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2022-03-01沐雪多租宝商城源码从.NetCore3.1升级到.Net6的步骤
- 2024-05-08首个适配Visual Studio平台的国产智能编程助手CodeGeeX正式上线!C#程序员必备效率神器!
- 2024-03-30C#设计模式之十六迭代器模式(Iterator Pattern)【行为型】
- 2024-03-29c# datetime tryparse
- 2024-02-21list find index c#
- 2024-01-24convert toint32 c#
- 2024-01-24Advanced .Net Debugging 1:你必须知道的调试工具
- 2024-01-24.NET集成IdGenerator生成分布式全局唯一ID
- 2024-01-23用CI/CD工具Vela部署Elasticsearch + C# 如何使用
- 2024-01-23.NET开源的简单、快速、强大的前后端分离后台权限管理系统