private void button2_Click(object sender, EventArgs e)
{
Thread t = new Thread(new ThreadStart(ThreadMethod));
t.Start();
}
private delegate void setText();
void ThreadMethod()
{
setText d = new setText(Threading);
this.Invoke(d);
}
void Threading()
{
while (true)
{
try
{
//MessageBox.Show(GetLocalIp());
int server_port = 12345;
string server_ip = GetLocalIp();
IPAddress localhost_ip = IPAddress.Parse(GetLocalIp());//将 IP 地址字符串转换为 IPAddress 实例
IPEndPoint server_ipe = new IPEndPoint(localhost_ip, server_port);//将网络端点表示为 IP 地址和端口号。
Socket server_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
server_socket.Bind(server_ipe);//绑定
server_socket.Listen(50);//参数指定队列中最多可容纳的等待接受的传入连接
Socket temp = server_socket.Accept();
clientip = (IPEndPoint)temp.RemoteEndPoint;
//MessageBox.Show("Connect success!");
//while (true)
//{
string recvStr = "";
byte[] recvBytes = new byte[1024];
int bytes;
bytes = temp.Receive(recvBytes);// 接收指定字节数的数据,并将数据存入接收缓冲区。
if (bytes == 0)
{
server_socket.Close();
temp.Close();
MessageBox.Show("退出");
break;
}
recvStr = Encoding.UTF8.GetString(recvBytes);
textBox1.Text += recvStr;
textBox1.Text += System.Environment.NewLine;
textBox1.Update();
BeepUp.Beep(500, 700);
this.BringToFront();
this.Focus();
//}
//string server_sendStr = this.textBox2.Text;
//byte[] server_sendbytes = Encoding.UTF8.GetBytes(server_sendStr);
//temp.Send(server_sendbytes);
temp.Close();
server_socket.Close();
}
catch (ArgumentNullException es)
{
Console.WriteLine("ArgumentNullException: {0}", es);
}
catch (SocketException es)
{
Console.WriteLine("SocketException: {0}", es);
}
Console.ReadLine();
}
}