⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 form1.cs.bak

📁 这是一个用c#做的聊天室,有服务器和客户端,采用多线程技术
💻 BAK
字号:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace AsyncTcpClient
{
    public partial class Form1 : Form
    {
        //标志客户端是否登出
		private bool isLive = false;
        private TcpClient client;
        private NetworkStream ns;
        //创建手动重置对象对线程进行管理
		private ManualResetEvent allDone = new ManualResetEvent(false);
		//使用代理来解决托管模式下的跨线程控件调用问题
		private delegate void SetListBoxCallBack(string str);
        //声明代理的对象 
		private SetListBoxCallBack setlistboxcallback;
        private delegate void SetRichTextBoxReceiveCallBack(string str);
        private SetRichTextBoxReceiveCallBack setRichTextBoxReceiveCallBack;
        public Form1()
        {
            InitializeComponent();
            //注册相应的回调函数,当代理被触发时被系统调用
			setlistboxcallback = new SetListBoxCallBack(SetListBox);
            setRichTextBoxReceiveCallBack = new SetRichTextBoxReceiveCallBack(SetRichTextBoxReceive);
        }

        private void buttonConnect_Click(object sender, EventArgs e)
        {
            //创建TcpClient对象,准备进行连接
			client = new TcpClient(AddressFamily.InterNetwork);
            IPAddress[] IP = Dns.GetHostAddresses(Dns.GetHostName());
            //注册异步方法BeginConnect的回调函数ConnectCallBack
			AsyncCallback connectCallBack = new AsyncCallback(ConnectCallBack);
            //允许其他等待的线程阻塞
			allDone.Reset();
            client.BeginConnect(IP[0],51888,connectCallBack,client);
            //在拥有此控件的基础窗口句柄的线程上执行委托
			listBoxStatus.Invoke(setlistboxcallback,string.Format("本机终结点:{0}",client.Client.LocalEndPoint));
            listBoxStatus.Invoke(setlistboxcallback,"开始与服务器连接");
            //使线程等待,直到收到信号
			allDone.WaitOne();
        }
		//完成连接的回调函数
        private void ConnectCallBack(IAsyncResult iar)
        {
			//使等待的线程可以继续执行下去
            allDone.Set();
            try
            {
                client = (TcpClient)iar.AsyncState;
                client.EndConnect(iar);
                listBoxStatus.Invoke(setlistboxcallback, string.Format("与服务器{0}连接成功", client.Client.RemoteEndPoint));
                //得到进行数据读写的网络流
				ns = client.GetStream();
                DataRead dataRead = new DataRead(ns, client.ReceiveBufferSize);
                ns.BeginRead(dataRead.msg, 0, dataRead.msg.Length, ReadCallBack, dataRead);
            }
            catch(Exception e)
            {
                listBoxStatus.Invoke(setlistboxcallback,e.Message);
                return;
            }
        }
        private void ReadCallBack(IAsyncResult iar)
        {
            try
            {
                DataRead dataRead = (DataRead)iar.AsyncState;
                int recv = dataRead.ns.EndRead(iar);
                richTextBoxRecv.Invoke(setRichTextBoxReceiveCallBack,Encoding.UTF8.GetString(dataRead.msg,0,recv));
                if (isLive == false)
                {
                    dataRead = new DataRead(ns,client.ReceiveBufferSize);
                    ns.BeginRead(dataRead.msg,0,dataRead.msg.Length,ReadCallBack,dataRead);
                }
            }
            catch(Exception e)
            {
                listBoxStatus.Invoke(setlistboxcallback,e.Message);
            }
        }
        private void SendString(string str)
        {
            try
            {
                byte[] bytesdata = Encoding.ASCII.GetBytes(str + "\r\n");
                ns.BeginWrite(bytesdata, 0, bytesdata.Length, new AsyncCallback(SendCallBack), ns);
                ns.Flush();
            }
            catch(Exception e)
            {
                listBoxStatus.Items.Add(e.Message);
            }
        }
        private void SendCallBack(IAsyncResult iar)
        {
            try
            {
                ns.EndWrite(iar);
            }
            catch (Exception e)
            {
                listBoxStatus.Invoke(setlistboxcallback, e.Message);
            }
        }
        private void SetListBox(string str)
        {
            listBoxStatus.Items.Add(str);
            listBoxStatus.SelectedIndex = listBoxStatus.Items.Count - 1;
            listBoxStatus.ClearSelected();
        }
        private void SetRichTextBoxReceive(string str)
        {
            richTextBoxRecv.AppendText(str);
        }

        private void buttonSend_Click(object sender, EventArgs e)
        {
            SendString(richTextBoxSend.Text);
            richTextBoxSend.Clear();
        }
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            isLive = true;
            allDone.Set();
        }

    
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -