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(); Invoke((MethodInvoker)delegate
{
button1.BackColor = Color.ForestGreen;
});
while (true)
{
Socket client = server.Accept();
byte[] buffer = new byte[];
int bytes = client.Receive(buffer, buffer.Length, SocketFlags.None); StringBuilder sb = new StringBuilder();
for (int i = ; 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, , bytes),
sb.ToString(),
client.LocalEndPoint);
File.AppendAllText(filePath, str);
textBox1.Text += str;
Application.DoEvents();
}); client.Send(new byte[] { (byte)'O', (byte)'K' }, );
client.Close();
}
}).ContinueWith((task) => {
if(task.Exception !=null)
Invoke((MethodInvoker)delegate
{
textBox1.Text += "\r\n错误:"+ task.Exception.InnerException.Message;
});
});
}
Task 异常处理可以参考:https://www.cnblogs.com/tianma3798/p/7003862.html