C#.net udp点对点聊天程序

客户端向服务器发起连接:

                //设置服务IP,设置UDP端口号
                ipep = new IPEndPoint(IPAddress.Parse(textBox1.Text), int.Parse(textBox2.Text)); //第一个参数是服务器ip地址,第二个参数是服务器端口号
                
                //定义网络类型,数据连接类型和网络协议UDP
                server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                Thread th = new Thread(new ThreadStart(myListen));	//建立一个线程,监听来自服务器的消息
                th.IsBackground = true;					//IsBackground设置为true,则程序退出时,这个线程也会结束,否则就会一直开启
                th.Start();

客户端监听来自服务器的消息:

private void myListen()
        {
            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
            EndPoint Remote = (EndPoint)sender;
            

            
            while (true)
            {                
                if (ena)		//只有首先发送了,连接才能建立起来,所以ena在发送完第一条消息后设置为true
                {
                    byte[] data = new byte[1024];
                    int recv = server.ReceiveFrom(data, ref Remote);
                    richTextBox1.AppendText(Encoding.Default.GetString(data));
                }
            }
        }

客户端向服务器发送消息:

byte[] b = Encoding.Default.GetBytes(textBox3.Text + ":\n" + textBox7.Text+"\n");
            server.SendTo(b, b.Length, SocketFlags.None, ipep);
            richTextBox1.AppendText(textBox3.Text + ":\n" + textBox7.Text + "\n");
            ena = true;

服务器开始监听:

                //得到本机IP,设置UDP端口号         
                ipep2 = new IPEndPoint(IPAddress.Any, int.Parse(textBox9.Text));
                newsock2 = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

                //绑定网络地址
                newsock2.Bind(ipep2);

                Thread thread = new Thread(new ThreadStart(serverListen));		//监听来自客户端发来的消息
                thread.IsBackground = true;
                thread.Start();

服务器监听来自客户端发来的消息:

//得到客户机IP                
            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
            Remote = (EndPoint)(sender);
            
            while (true)
            {
                byte[] data = new byte[1024];
                newsock2.ReceiveFrom(data, ref Remote);
                button4.Enabled = true;
//              textBox4.Text = sender.Address.ToString();  //目前无法通过这样获得客户端ip和端口号
//              textBox5.Text = sender.Port + "";
                richTextBox2.AppendText(Encoding.Default.GetString(data));
            }
服务器想客户端发送消息:

byte[] b = Encoding.Default.GetBytes(textBox6.Text + ":\n" + textBox8.Text+ "\n");
            //发送信息
            newsock2.SendTo(b, b.Length, SocketFlags.None, Remote);
            richTextBox2.AppendText(textBox6.Text + ":\n" + textBox8.Text + "\n");

截图如下:




源码地址:

http://download.csdn.net/detail/a578559967/4203894

你可能感兴趣的:(thread,socket,服务器,网络协议,byte,textbox)