C#中Socket通信用法实例详解
本文实例讲述了C#中Socket通信用法。分享给大家供大家参考。具体如下:
一、UDP方式:
服务器端代码:
static void Main(string[] args) { int recv; byte[] data = new byte[1024]; IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);//定义一网络端点 Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);//定义一个Socket newsock.Bind(ipep);//Socket与本地的一个终结点相关联 Console.WriteLine("Waiting for a client.."); IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);//定义要发送的计算机的地址 EndPoint Remote = (EndPoint)(sender);// recv = newsock.ReceiveFrom(data, ref Remote);//接受数据 Console.WriteLine("Message received from{0}:", Remote.ToString()); Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv)); string welcome = "Welcome to my test server!"; data = Encoding.ASCII.GetBytes(welcome); newsock.SendTo(data, data.Length, SocketFlags.None, Remote); while (true) { data = new byte[1024]; recv = newsock.ReceiveFrom(data, ref Remote); Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv)); newsock.SendTo(data, recv, SocketFlags.None, Remote); } }
客户端代码:
void MainInfo() { byte[] data = new byte[1024];//定义一个数组用来做数据的缓冲区 string input, stringData; IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("192.168.1.21"), 9050); Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); string welcome = "Hello,are you there?"; data = Encoding.ASCII.GetBytes(welcome); server.SendTo(data, data.Length, SocketFlags.None, ipep);//将数据发送到指定的终结点 IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); EndPoint Remote = (EndPoint)sender; data = new byte[1024]; int recv = server.ReceiveFrom(data, ref Remote);//接受来自服务器的数据 Console.WriteLine("Message received from{0}:", Remote.ToString()); Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv)); while (true)//读取数据 { input = richTextBox1.Text;//从键盘读取数据 if (input == "text")//结束标记 { break; } server.SendTo(Encoding.ASCII.GetBytes(input), Remote);//将数据发送到指定的终结点Remote data = new byte[1024]; recv = server.ReceiveFrom(data, ref Remote);//从Remote接受数据 stringData = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine(stringData); } Console.WriteLine("Stopping client"); server.Close(); }
二、TCP方式:
服务器端代码:
Socket serverSocket = null; Thread clientThread = null; Socket clientSocket = null; Thread thread = null; IPAddress ips = null; PEndPoint ipep = null; void ServerStart() { ips = Dns.GetHostAddresses(Dns.GetHostName())[0]; //创建IPEndPoint实例 ipep = new IPEndPoint(ips, 9050); //创建一个套接字 serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); serverSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); //将所创建的套接字与IPEndPoint绑定 serverSocket.Bind(ipep); //设置套接字为收听模式 serverSocket.Listen(20); while (listenalive) { try { //在套接字上接收接入的连接 clientSocket = serverSocket.Accept(); clientThread = new Thread(new ParameterizedThreadStart(ReceiveData)); clientThread.Start(clientSocket); } catch (Exception ex) { WriteErrorLog(ex.Message); serverSocket.Close(); serverSocket = null; } } } static void ReceiveData(object obj) { bool keepalive = true; Socket s = obj as Socket; Byte[] buffer = new Byte[1024]; //根据收听到的客户端套接字向客户端发送信息 IPEndPoint clientep = (IPEndPoint)s.RemoteEndPoint; Console.WriteLine("客户端ip:" + clientep.Address + " 端口:" + clientep.Port); string welcome = "连接服务器成功"; buffer = System.Text.Encoding.Unicode.GetBytes(welcome); //向客户端发送“连接服务器成功”消息 s.Send(buffer, buffer.Length, SocketFlags.None); buffer = new Byte[1024]; int bufLen = 0; string content = string.Empty; while (true) { //在套接字上接收客户端发送的信息 bufLen = 0; try { bufLen = s.Receive(buffer); if (bufLen == 0) { break; } content += System.Text.Encoding.Unicode.GetString(buffer, 0, bufLen); } catch (Exception ex) { break; ; } } Send(s, content); s = null; buffer = null; clientep = null; Thread.CurrentThread.Abort(); }
客户端代码:
void Send(string content) { byte[] data = new byte[1024]; newclient = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp); ie = new System.Net.IPEndPoint(System.Net.IPAddress.Parse(ipadd), port);//服务器的IP和端口 try { //因为客户端只是用来向特定的服务器发送信息,所以不需要绑定本机的IP和端口。不需要监听。 newclient.Connect(ie); } catch (System.Net.Sockets.SocketException e) { Console.WriteLine(e.ToString()); return; } int recv = newclient.Receive(data); //连接服务器成功 string stringdata = System.Text.Encoding.Unicode.GetString(data, 0, recv); if (stringdata == "连接服务器成功") { newclient.Send(System.Text.Encoding.Unicode.GetBytes(content)); newclient.Shutdown(System.Net.Sockets.SocketShutdown.Send); data = new byte[1024]; recv = newclient.Receive(data); string result = System.Text.Encoding.Unicode.GetString(data, 0, recv); newclient.Shutdown(System.Net.Sockets.SocketShutdown.Receive); newclient.Close(); MessageBox.Show(result); } else { MessageBox.Show("连接服务器失败", "友情提示"); } }
希望本文所述对大家的C#程序设计有所帮助。
上一篇:C#获取客户端相关信息实例总结
栏 目:C#教程
本文标题:C#中Socket通信用法实例详解
本文地址:https://www.xiuzhanwang.com/a1/C_jiaocheng/6958.html
您可能感兴趣的文章
- 01-10C#通过反射获取当前工程中所有窗体并打开的方法
- 01-10C#实现Winform中打开网页页面的方法
- 01-10C#实现由四周向中心缩小的窗体退出特效
- 01-10Extjs4如何处理后台json数据中日期和时间
- 01-10C#中DataGridView常用操作实例小结
- 01-10C#编程获取资源文件中图片的方法
- 01-10asp.net中XML如何做增删改查操作
- 01-10C#利用反射技术实现去掉按钮选中时的边框效果
- 01-10C#中查找Dictionary中的重复值的方法
- 01-10C#实现子窗体与父窗体通信方法实例总结
阅读排行
本栏相关
- 01-10C#通过反射获取当前工程中所有窗体并
- 01-10关于ASP网页无法打开的解决方案
- 01-10WinForm限制窗体不能移到屏幕外的方法
- 01-10WinForm绘制圆角的方法
- 01-10C#实现txt定位指定行完整实例
- 01-10WinForm实现仿视频播放器左下角滚动新
- 01-10C#停止线程的方法
- 01-10C#实现清空回收站的方法
- 01-10C#通过重写Panel改变边框颜色与宽度的
- 01-10C#实现读取注册表监控当前操作系统已
随机阅读
- 01-10SublimeText编译C开发环境设置
- 08-05织梦dedecms什么时候用栏目交叉功能?
- 04-02jquery与jsp,用jquery
- 08-05dedecms(织梦)副栏目数量限制代码修改
- 01-10C#中split用法实例总结
- 01-10delphi制作wav文件的方法
- 08-05DEDE织梦data目录下的sessions文件夹有什
- 01-11Mac OSX 打开原生自带读写NTFS功能(图文
- 01-10使用C语言求解扑克牌的顺子及n个骰子
- 01-11ajax实现页面的局部加载