简单P2P聊天
1 //监听
2 private void Listen()
3 {
4 try
5 {
6 tcpl = new TcpListener(4567);
7 tcpl.Start();
8 statusBar1.Text = "正在监听
";
9
10 while(listenerRun)
11 {
12 Socket s = tcpl.AcceptSocket();
13 Byte[] stream = new Byte[80];
14 int i=s.Receive(stream) ;
15 string message = System.Text.Encoding.UTF8.GetString(stream);
16 richTextBox1.AppendText(message);
17 }
18 }
19 catch(System.Security.SecurityException)
20 {
21 MessageBox.Show("防火墙安全错误!","错误",
22 MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
23 }
24 catch(Exception)
25 {
26 statusBar1.Text = "已停止监听!";
27 }
28 }
2 private void Listen()
3 {
4 try
5 {
6 tcpl = new TcpListener(4567);
7 tcpl.Start();
8 statusBar1.Text = "正在监听
";9
10 while(listenerRun)
11 {
12 Socket s = tcpl.AcceptSocket();
13 Byte[] stream = new Byte[80];
14 int i=s.Receive(stream) ;
15 string message = System.Text.Encoding.UTF8.GetString(stream);
16 richTextBox1.AppendText(message);
17 }
18 }
19 catch(System.Security.SecurityException)
20 {
21 MessageBox.Show("防火墙安全错误!","错误",
22 MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
23 }
24 catch(Exception)
25 {
26 statusBar1.Text = "已停止监听!";
27 }
28 }
1 //发送
2 private void Send()
3 {
4 try
5 {
6 string msg = "<"+textBox3.Text+">"+textBox2.Text;
7 TcpClient tcpc = new TcpClient(textBox1.Text, 4567);
8 NetworkStream tcpStream = tcpc.GetStream();
9
10 StreamWriter reqStreamW = new StreamWriter(tcpStream);
11 reqStreamW.Write(msg);
12 reqStreamW.Flush();
13 tcpStream.Close();
14 tcpc.Close();
15 richTextBox1.AppendText(msg);
16 textBox2.Clear();
17 }
18 catch(Exception)
19 {
20 statusBar1.Text = "目标计算机拒绝连接请求!";
21 }
22 }
2 private void Send()
3 {
4 try
5 {
6 string msg = "<"+textBox3.Text+">"+textBox2.Text;
7 TcpClient tcpc = new TcpClient(textBox1.Text, 4567);
8 NetworkStream tcpStream = tcpc.GetStream();
9
10 StreamWriter reqStreamW = new StreamWriter(tcpStream);
11 reqStreamW.Write(msg);
12 reqStreamW.Flush();
13 tcpStream.Close();
14 tcpc.Close();
15 richTextBox1.AppendText(msg);
16 textBox2.Clear();
17 }
18 catch(Exception)
19 {
20 statusBar1.Text = "目标计算机拒绝连接请求!";
21 }
22 }
浙公网安备 33010602011771号