private void OpenSocket(int port) { Task.Factory.StartNew(() => { server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint local = new IPEndPoint(IPAddress.Parse("127.1"), port); server.Bind(local); server.Listen(10); Invoke((MethodInvoker)delegate { button1.BackColor = Color.ForestGreen; }); while (true) { Socket client = server.Accept(); byte[] buffer = new byte[1024]; int bytes = client.Receive(buffer, buffer.Length, SocketFlags.None); StringBuilder sb = new StringBuilder(); for (int i = 0; i < bytes; i++) { sb.AppendFormat("{0} ", buffer[i].ToString("x2")); } Invoke((MethodInvoker)delegate { string filePath = AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\') + "\log.txt"; string str = string.Format(" {0} 接收到来自 {1} 的消息:{2} {3} 发送到:{4}", DateTime.Now.ToString("HH:mm"), client.RemoteEndPoint, Encoding.ASCII.GetString(buffer, 0, bytes), sb.ToString(), client.LocalEndPoint); File.AppendAllText(filePath, str); textBox1.Text += str; Application.DoEvents(); }); client.Send(new byte[] { (byte)'O', (byte)'K' }, 0); client.Close(); } }).ContinueWith((task) => { if(task.Exception !=null) Invoke((MethodInvoker)delegate { textBox1.Text += " 错误:"+ task.Exception.InnerException.Message; }); }); }
Task 异常处理可以参考:https://www.cnblogs.com/tianma3798/p/7003862.html