这时正解:- Socket socketwatch = null;
- private void btn_connection_Click(object sender, RoutedEventArgs e)
- {
-
- //创建服务端负责监听的Socket
- socketwatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- IPAddress address = IPAddress.Parse(txt_ip.Text.Trim());//获取监听的IP地址
- IPEndPoint endpoint = new IPEndPoint(address, int.Parse(txt_port.Text.Trim()));
- socketwatch.Bind(endpoint);
- socketwatch.Listen(10);
- Thread listenthread = new Thread(Listen);
- listenthread.IsBackground = true;
- listenthread.Start();
- txt_info.AppendText("服务器启动成功!等待链接……\n");
- }
- Socket socketconmunication = null;
- private void Listen()
- {
- while (true)
- {
- socketconmunication = socketwatch.Accept();
- ShowMsg("客户端建立链接成功"+socketconmunication.RemoteEndPoint.ToString()+"\n");
- }
- }
- delegate void ListenDelegate(string msg);
- private void ShowMsg(string msg)
- {
- if (Dispatcher.Thread != Thread.CurrentThread)
- {
- Dispatcher.Invoke(new ListenDelegate(ShowMsg),msg);
- }
- else
- {
- txt_info.AppendText(msg);
- }
- }
复制代码 |