socket相关
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Windows.Forms; //服务器端的程序 namespace AuoProduce4CMN { public partial class Form1 : Form { List<Socket> clientProxSocketList = new List<Socket>(); public Form1() { InitializeComponent(); } private void btn_start_Click(object sender, EventArgs e) { //socket服务器端逻辑 //1、创建socket对象(用于服务器端监听) //para1:使用ipv4的网络寻址协议。 //para2:数据传输方式 stream流式协议. //para3:通信协议的设置(tcp协议) Socket serverSoc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //2、绑定IP和端口 IPAddress ip = IPAddress.Parse("");//将字符串转换成IP地址 IPEndPoint ipendPoint = new IPEndPoint(ip, int.Parse(""));//给出端口号 serverSoc.Bind(ipendPoint); //3、开启侦听 serverSoc.Listen(10);//挂起队列的最大长度。超过这个数之后,后面的链接请求会返回错误消息 //4、开始接受客户端连接 ThreadPool.QueueUserWorkItem(new WaitCallback(this.SartAcceptClient), serverSoc); } public void SartAcceptClient(object state) { var serverSoc = (Socket)state; while (true) { Socket proxSocket = serverSoc.Accept();//accept方法一执行,当前线程阻塞。一直等客户端连接上。 clientProxSocketList.Add(proxSocket);//当收到一个客户端请求的时候,将它放到这个队列中去 //不停的接收当前链接的客户端发送来的消息 ThreadPool.QueueUserWorkItem(new WaitCallback(this.ReceiveData), proxSocket); //proxSocket.RemoteEndPoint.ToString();客户端信息。 //proxSocket.Shutdown(SocketShutdown.Both);//关闭服务器端的socket对象。发送一个0字节的消息,告知对方,此次通信结束。 //proxSocket.Close(); //serverSoc.Close(); } } private void button1_Click(object sender, EventArgs e) { foreach (var proxSocket in clientProxSocketList) { if (proxSocket.Connected) { //将要发送的字符串转换成字节数组 byte[] data = Encoding.Default.GetBytes("Hello World"); proxSocket.Send(data, 0, data.Length, SocketFlags.None);//最后一个参数,当在同一个局域网内进行访问的时候,就使用None,如果是外网访问的话,那么需要设置其他参数 } } } public void ReceiveData(object obj) { var proxSocket = (Socket)obj; byte[] data = new byte[1024 * 1024];//创建1M的缓冲区 while (true) { int receiveDataLen = 0; try { receiveDataLen = proxSocket.Receive(data, 0, data.Length - 1, SocketFlags.None);//接收客户端数据。实际接收数据的字节数 if (receiveDataLen == 0)//正常退出 { clientProxSocketList.Remove(proxSocket); StopConnect(proxSocket); return;//让方法结束,等同于让该线程结束。 } //接收到的字符串 string strMsg = Encoding.Default.GetString(data, 0, receiveDataLen); } catch (Exception) { clientProxSocketList.Remove(proxSocket); StopConnect(proxSocket); return; } } } private void StopConnect(Socket proxSocket) { try { if (proxSocket.Connected) { proxSocket.Shutdown(SocketShutdown.Both); proxSocket.Close(100);//超过100秒没有正常关闭,那就强制关闭 } } catch (Exception) { throw; } } } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
void ServerSocket() { //TcpListener是对socket 进行了一层封装,这个类里自己会去创建一个socket对象。 TcpListener serverSocket = new TcpListener(IPAddress.Parse("192.168.1.33"), 10000); //开始进行监听 serverSocket.Start(); //等待客户端进行连接 TcpClient clientSocket = serverSocket.AcceptTcpClient(); //取得客户端发送过来的数据。 NetworkStream stream = clientSocket.GetStream();//得到一个网络流。从该流中可以获取到客户单发送过来的数据。 byte[] data = new byte[1024];//创建1M缓存区(容器),用来承接数据。 int len = stream.Read(data, 0, 1024);//读取数据。 string msg = Encoding.UTF8.GetString(data, 0, len); stream.Close();//关闭流 clientSocket.Close();//关闭与客户端的连接。 serverSocket.Stop();//停止监听。 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Windows.Forms; namespace AuoProduce4CMN { //客户端 public partial class Form2 : Form { public Form2() { InitializeComponent(); } public Socket ClientSocket { get; set; } private void button2_Click(object sender, EventArgs e) { //客户端连接服务器端 //1创建socket对象 Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); ClientSocket = socket; //2连接服务器端 try { socket.Connect(IPAddress.Parse("strIP"), int.Parse("strPort")); } catch (Exception) { Thread.Sleep(500); button2_Click(this, e); return; } Thread thread = new Thread(new ParameterizedThreadStart(ReceiveData)); thread.IsBackground = true; thread.Start(ClientSocket); } private void button1_Click(object sender, EventArgs e) { if (ClientSocket.Connected) { //将要发送的字符串转换成字节数组 byte[] data = Encoding.Default.GetBytes("Hello World"); ClientSocket.Send(data, 0, data.Length, SocketFlags.None);//最后一个参数,当在同一个局域网内进行访问的时候,就使用None,如果是外网访问的话,那么需要设置其他参数 } } public void ReceiveData(object obj) { var proxSocket = (Socket)obj; byte[] data = new byte[1024 * 1024];//创建1M的缓冲区 while (true) { int receiveDataLen = 0; try { receiveDataLen = proxSocket.Receive(data, 0, data.Length - 1, SocketFlags.None);//接收客户端数据。实际接收数据的字节数 if (receiveDataLen == 0)//正常退出 { StopConnect(); return;//让方法结束,等同于让该线程结束。 } //接收到的字符串 string strMsg = Encoding.Default.GetString(data, 0, receiveDataLen); } catch (Exception) { StopConnect(); return; } } } private void StopConnect() { try { if (ClientSocket.Connected) { ClientSocket.Shutdown(SocketShutdown.Both); ClientSocket.Close(100);//超过100秒没有正常关闭,那就强制关闭 } } catch (Exception) { throw; } } private void Form2_FormClosing(object sender, FormClosingEventArgs e) { StopConnect(); } } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
TcpClient clientServer = new TcpClient("192.168.1.33", 10000); NetworkStream stream = clientServer.GetStream(); byte[] data = Encoding.UTF8.GetBytes("要发送的信息"); stream.Write(data, 0, data.Length); stream.Close(); clientServer.Close();