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

📄 form1.cs

📁 visual c# 网络编程技术与实践实例包括几个源码
💻 CS
字号:
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.IO;
using System.Threading;

namespace AsyncTcpServer
{
    public partial class Form1 : Form
    {
        private bool isExit = false;
        System.Collections.ArrayList clientlist = new System.Collections.ArrayList();
        TcpListener listener;
        private delegate void SetListBoxCallBack(string str);
        private SetListBoxCallBack setlistboxcallback;
        private delegate void SetRichTextBoxCallBack(string str);
        private SetRichTextBoxCallBack setrichtextboxcallback;
        private delegate void SetComboBoxCallBack(string str);
        private SetComboBoxCallBack setcomboboxcallback;
        private delegate void RemoveComboBoxItemsCallBack(DataReadWrite datareadwrite);
        private RemoveComboBoxItemsCallBack removecomboboxcallback;
        private ManualResetEvent allDone=new ManualResetEvent(false);
        public Form1()
        {
            InitializeComponent();
            //listBoxStatus.HorizontalScrollbar = true;
            setlistboxcallback = new SetListBoxCallBack(SetListBox);
            setrichtextboxcallback = new SetRichTextBoxCallBack(SetReceiveText);
            setcomboboxcallback = new SetComboBoxCallBack(SetComboBox);
            removecomboboxcallback = new RemoveComboBoxItemsCallBack(RemoveComboBoxItems);
        }

        private void buttonStart_Click(object sender, EventArgs e)
        {
            Thread myThread = new Thread(new ThreadStart(AcceptConnection));
            myThread.Start();
            buttonStart.Enabled = false;
            buttonStop.Enabled = true;
        }
        private void AcceptConnection()
        {
            IPAddress[] ip = Dns.GetHostAddresses(Dns.GetHostName());
            // TcpListener server = new TcpListener(port);
            listener = new TcpListener(ip[0], 51888);
            listener.Start();
            while (isExit == false)
            {
                try
                {
                    allDone.Reset();
                    AsyncCallback callback = new AsyncCallback(AcceptTcpClientCallBack);
                    listBoxStatus.Invoke(setlistboxcallback, "开始等待连接");
                    listener.BeginAcceptTcpClient(callback, listener);
                    allDone.WaitOne();
                }
                catch(Exception e)
                {
                    listBoxStatus.Invoke(setlistboxcallback,e.Message);
                    break;
                }
            }
        }
        private void AcceptTcpClientCallBack(IAsyncResult iar)
        {
            try
            {
                allDone.Set();
                TcpListener mylistener = (TcpListener)iar.AsyncState;
                TcpClient client = mylistener.EndAcceptTcpClient(iar);
                listBoxStatus.Invoke(setlistboxcallback, "已接受客户连接:" + client.Client.RemoteEndPoint);
                //listBoxStatus.Items.Add( "已接受客户连接:" + client.Client.RemoteEndPoint);
                comboBox1.Invoke(setcomboboxcallback, client.Client.RemoteEndPoint.ToString());
                DataReadWrite datareadwrite = new DataReadWrite(client);
                clientlist.Add(datareadwrite);
                SendString(datareadwrite, "服务器已经接受连接,请通话");
                datareadwrite.ns.BeginRead(datareadwrite.read, 0, datareadwrite.read.Length, ReadCallBack, datareadwrite);
            }
            catch (Exception e)
            {
                listBoxStatus.Invoke(setlistboxcallback,e.Message);
                return;
            }
        }
        private void ReadCallBack(IAsyncResult iar)
        {
            try
            {
                DataReadWrite datareadwrite = (DataReadWrite)iar.AsyncState;
                int recv = datareadwrite.ns.EndRead(iar);
                richTextBoxRecv.Invoke(setrichtextboxcallback, string.Format("[来自{0}]{1}", datareadwrite.client.Client.RemoteEndPoint, Encoding.UTF8.GetString(datareadwrite.read, 0, recv)));
                if (isExit == false)
                {
                    datareadwrite.InitReadArray();
                    datareadwrite.ns.BeginRead(datareadwrite.read, 0, datareadwrite.read.Length, ReadCallBack, datareadwrite);
                }
            }
            catch (Exception e)
            {
                listBoxStatus.Invoke(setlistboxcallback,e.Message);
            }
        }
        private void SendString(DataReadWrite datareadwrite, string str)
        {
            try
            {
                datareadwrite.write = Encoding.ASCII.GetBytes(str + "\r\n");
                datareadwrite.ns.BeginWrite(datareadwrite.write, 0, datareadwrite.write.Length, new AsyncCallback(SendCallBack), datareadwrite);
                datareadwrite.ns.Flush();
                listBoxStatus.Invoke(setlistboxcallback, string.Format("向{0}发送:{1}", datareadwrite.client.Client.RemoteEndPoint, str));
            }
            catch (Exception e)
            {
                listBoxStatus.Items.Add(e.Message);
            }
        }
        private void SendCallBack(IAsyncResult iar)
        {
            DataReadWrite datareadwrite = (DataReadWrite)iar.AsyncState;
            try
            {
                datareadwrite.ns.EndWrite(iar);
            }
            catch (Exception e)
            {
                listBoxStatus.Invoke(setlistboxcallback,e.Message);
                comboBox1.Invoke(removecomboboxcallback,datareadwrite);
            }
        }
        private void RemoveComboBoxItems(DataReadWrite datareadwrite)
        {
            int index = clientlist.IndexOf(datareadwrite);
            comboBox1.Items.RemoveAt(index);
        }
        private void SetListBox(string str)
        {
            listBoxStatus.Items.Add(str);
            listBoxStatus.SelectedIndex = listBoxStatus.Items.Count - 1;
            listBoxStatus.ClearSelected();
        }
        private void SetReceiveText(string str)
        {
            richTextBoxRecv.AppendText(str);
        }
        private void SetComboBox(object obj)
        {
            comboBox1.Items.Add(obj);
        }

        private void buttonStop_Click(object sender, EventArgs e)
        {
            isExit = true;
            allDone.Set();
            buttonStart.Enabled = true;
            buttonStop.Enabled = false;
        }

        private void buttonSend_Click(object sender, EventArgs e)
        {
            int index = comboBox1.SelectedIndex;
            if (index == -1)
            {
                MessageBox.Show("请先选择接收方,再单击发送");
            }
            else
            {
                DataReadWrite obj = (DataReadWrite)clientlist[index];
                SendString(obj,richTextBoxSend.Text);
                richTextBoxSend.Clear();
            }
        }
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            buttonStop_Click(null,null);
        }


       
    }
}

⌨️ 快捷键说明

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