Socket编程(三)- 实现简单的聊天程序

1.服务器

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace Server
{
    public partial class Form1 : Form
    {
        private Socket server;   //监听
        Socket clientSocket;     //通信
        public Form1()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
        }

        //服务器给客户端发送消息
        private void button1_Click(object sender, EventArgs e)
        {
            clientSocket.Send(Encoding.UTF8.GetBytes(writeBox.Text));
            showBox.Text += writeBox.Text + "\r\n";
            writeBox.Text = "";
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            
            try
            {
                server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress address = new IPAddress(new Byte[] { 127, 0, 0, 1 });
                EndPoint point = new IPEndPoint(address, 7788);   //封装IP和端口号
                server.Bind(point);
                server.Listen(100);
                Thread th = new Thread(socketListen);
                th.IsBackground = true;
                th.Start();
            }
            catch
            {
            }          
        }
        
        void socketListen()
        {           
            while (true)
            {
                try
                {
                    clientSocket = server.Accept();  //等待,直到接收到客户端的请求,并为之创建一个负责通信的socket
                    Thread th = new Thread(socketReceive);
                    th.IsBackground = true;
                    th.Start(clientSocket);
                }
                catch
                {                
                }               
            }
        }

        void socketReceive(object obj)
        {
            Socket clientSocket = obj as Socket;
            while (true)
            {
                try
                {
                    byte[] data = new byte[1024 * 1024];
                    int length = clientSocket.Receive(data);
                    if (length == 0)
                        break;
                    string message = Encoding.UTF8.GetString(data, 0, length);
                    showBox.Text += clientSocket.RemoteEndPoint.ToString() + ":" + message + "\r\n";
                    writeBox.Text = "";
                }
                catch
                {               
                }             
            }
        }
    }
}

2.客户端

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace Client
{
    public partial class Form1 : Form
    {
        Socket client = null;
        public Form1()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            client.Send(Encoding.UTF8.GetBytes(writeBox.Text));
            showBox.Text += writeBox.Text + "\r\n";
            writeBox.Text = "";
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                //创建客户端socket
                client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //发起建立连接的请求
                IPAddress address = IPAddress.Parse("127.0.0.1");
                EndPoint point = new IPEndPoint(address, 7788);
                client.Connect(point);
                //接收服务器的消息
                Thread th = new Thread(socketReceive);
                th.IsBackground = true;
                th.Start();
            }
            catch
            {              
            }           
        }

        void socketReceive()
        {
            while (true)
            {
                try
                {
                    byte[] data = new byte[1024 * 1024];
                    int length = client.Receive(data);   //length表示接收到的数据的长度
                    if (length == 0)
                        break;
                    string message = Encoding.UTF8.GetString(data, 0, length);
                    showBox.Text += client.RemoteEndPoint.ToString() + ":" + message + "\r\n";
                }
                catch 
                {                  
                }
            }
        }
    }
}

3.运行结果

Socket编程(三)- 实现简单的聊天程序_第1张图片

Socket编程(三)- 实现简单的聊天程序_第2张图片

4.分析

    该程序中,服务器可以一直监听客户端的连接,可以接收多条客户端发来的信息。但是有一个缺点,后来的客户端连接会覆盖掉先前的连接,即:服务器无法给较早连接进来的客户端发送信息。在后面的文章中,会解决这一问题。

 

 

你可能感兴趣的:(C#)