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("\r\n{0} 接收到來自 {1} 的消息:{2}\r\n{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 += "\r\n錯誤:"+ task.Exception.InnerException.Message; }); }); }
Task 異常處理能夠參考:http://www.javashuo.com/article/p-rofyxlwz-cp.htmlhtml