C# Socket建立
C#中建立Soket服务器。
static Socket newSoket; private static int mProt = 80;//端口 /// <summary> /// 初始化soket /// </summary> public void initSoket() { //服务器IP IPAddress ip = IPAddress.Parse("127.0.0.1"); //新建soket newSoket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); newSoket.Bind(new IPEndPoint(ip, mProt)); newSoket.Listen(20);//设定最多10个排队连接请求 listBox1.Items.Add(string.Format("监听{0}成功",newSoket.LocalEndPoint.ToString())); //通过Clientsoket发送数据 Thread myThread = new Thread(ListenCXlientConnect); myThread.IsBackground = true; myThread.Start(); } public static Dictionary<string, Socket> dicSocket = new Dictionary<string, Socket>();//保存socket public static void ListenCXlientConnect() { if (newSoket != null) { try { Socket clientSocket = newSoket.Accept();//为新建连接建立新的socket if (!dicSocket.ContainsKey(clientSocket.RemoteEndPoint.ToString()))//如果不包含就创建新的通信套接字 { dicSocket.Add(clientSocket.RemoteEndPoint.ToString(),clientSocket); Thread receiveThread = new Thread(ReceiveMessage); receiveThread.Start(clientSocket); receiveThread.IsBackground = true; } } catch(Exception ex) { } } } /// <summary> /// 接收消息 /// </summary> private static void ReceiveMessage(object clientSocket) { }