连续聊天

下面是实现了双向聊天的功能,并且使用了多线程,避免卡顿。

现在 WinForm 版本使用BackgroundWorker单独线程循环接收,发送在 UI 线程独立触发,突破了这个限制,可以自由双向聊天。

首先是服务器端

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;

namespace Service
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        IPAddress ip;
        TcpListener listener;
        TcpClient tcpClient;

        private void buttonStart_Click(object sender, EventArgs e)
        {
            this.backgroundWorker1.RunWorkerAsync();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            ip = IPAddress.Parse(this.textBoxIP.Text);//创建IP
            listener = new TcpListener(ip, Convert.ToInt32(this.textBoxPort.Text));//创建TCP监听对象
            listener.Start();
            this.textBoxInfo.Text = "服务器启动-" + DateTime.Now.ToShortTimeString() + "\r\n" + this.textBoxInfo.Text;
            tcpClient = listener.AcceptTcpClient();//中断 等待
            this.textBoxInfo.Text = "连接成功-" + DateTime.Now.ToShortTimeString() + "\r\n" + this.textBoxInfo.Text;

            NetworkStream stream = tcpClient.GetStream();
            byte[] byteArray = new byte[1024];
            while (true)
            {
                int length = stream.Read(byteArray, 0, 1024);//会把流里面的字节数组 放到byteArray里面
                                                             //length其实就是客户端发送的字节数组长度
                string receiveMessage = Encoding.Unicode.GetString(byteArray, 0, length);
                this.textBoxInfo.Text = "接收到:" + receiveMessage + "-" + DateTime.Now.ToShortTimeString() + "\r\n" + this.textBoxInfo.Text;
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

        }

        private void buttonSend_Click(object sender, EventArgs e)
        {
            string message = this.textBoxInput.Text;
            this.textBoxInfo.Text = "发送“" + message + "”-" + DateTime.Now.ToShortTimeString() + "\r\n" + this.textBoxInfo.Text;
            NetworkStream stream = tcpClient.GetStream();
            byte[] byteArray = Encoding.Unicode.GetBytes(message);
            stream.Write(byteArray, 0, byteArray.Length);//发送了字节数组
        }
    }
}
Code language: C# (cs)

然后是客户端

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;

namespace Client
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }
        TcpClient tcpClient;
        private void buttonStart_Click(object sender, EventArgs e)
        {
            tcpClient = new TcpClient();
            try
            {
                tcpClient.Connect(this.textBoxIP.Text, Convert.ToInt32(this.textBoxPort.Text));
                this.textBoxInfo.Text = "连接成功-" + DateTime.Now.ToShortTimeString() + "\r\n" + this.textBoxInfo.Text;
                this.backgroundWorker1.RunWorkerAsync();
            }
            catch (Exception ex)
            {
                MessageBox.Show("连接失败-"+ex.Message);
            }
        }

        private void buttonSend_Click(object sender, EventArgs e)
        {
            string message = this.textBoxInput.Text;
            this.textBoxInfo.Text = "发送“"+message+"”-" + DateTime.Now.ToShortTimeString() + "\r\n" + this.textBoxInfo.Text;
            NetworkStream stream = tcpClient.GetStream();
            byte[] byteArray = Encoding.Unicode.GetBytes(message);
            stream.Write(byteArray, 0, byteArray.Length);//发送了字节数组
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            NetworkStream stream = tcpClient.GetStream();
            byte[] byteArray = new byte[1024];
            while (true)
            {
                int length = stream.Read(byteArray, 0, 1024);//会把流里面的字节数组 放到byteArray里面
                                                             //length其实就是客户端发送的字节数组长度
                string receiveMessage = Encoding.Unicode.GetString(byteArray, 0, length);
                this.textBoxInfo.Text = "接收到:" + receiveMessage + "-" + DateTime.Now.ToShortTimeString() + "\r\n" + this.textBoxInfo.Text;
            }
        }
    }
}
Code language: C# (cs)

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注