private void button1_Click(object sender, EventArgs e)
{
//try
//{
//当点击开始监听的时候,在服务器端创建一个负责监听IP地址和端口号的Socket
Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ip = IPAddress.Any; //IPAddress.Parse(textBox1.Text);
//创建端口对象
IPEndPoint endPoint = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text));
socketWatch.Bind(endPoint);
ShowMsg("监听成功!");
socketWatch.Listen(10);
Thread th = new Thread(Listen);
th.IsBackground = true;
th.Start(socketWatch);
//}
//catch { }
}
void Listen(object o)
{
Socket socketWatch = o as Socket;
while (true)
{
//try
//{
//等待客户端的链接 并创建一个负责通讯的Socket
Socket socketSend = socketWatch.Accept();
ShowMsg(socketWatch.RemoteEndPoint.ToString() + ":链接成功!");
Thread th = new Thread(Recive);
th.IsBackground = true;
th.Start(socketSend);
//}
//catch { }
}
}
void Recive(object o)
{
Socket socketSend = o as Socket;
byte[] buffer = new byte[1024 * 1024 * 5];
while (true)
{
int i = socketSend.Receive(buffer);
if (i == 0)
{
break;
}
}
}
private void ShowMsg(string str)
{
txtLog.AppendText(str + "\r\n");
}
![图片说明](https://img-ask.csdn.net/upload/201505/25/1432560661_441639.jpg)