求C# TCP⼀IP 多用户的服务端程序

2024-12-16 12:49:11
推荐回答(2个)
回答1:

namespace SocketTest
{
    public partial class Server : Form
    {
        public Server()
        {
            InitializeComponent();
            TextBox.CheckForIllegalCrossThreadCalls = false;
            sockets = new SortedList();
        }
        Thread thread = null;
        Socket socket;//服务器 套接字
        SortedList sockets;//存放  套接字对象的键值对
        private void Server_Load(object sender, EventArgs e)
        {
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress ip = IPAddress.Parse("127.0.0.1");
            IPEndPoint endPoint = new IPEndPoint(ip, int.Parse("8888"));
            socket.Bind(endPoint);
            socket.Listen(10);

            thread = new Thread(MyCon);
            thread.IsBackground = true;
            thread.Start();
            ShowMsg("启动服务器");
            ShowMsg("等待客服端链接.......");
            //socket.Accept();
        }
        private void MyCon()
        {
            while (true)
            {
                Socket sok = socket.Accept();
                sockets.Add(sok.RemoteEndPoint.ToString(), sok);
                ShowMsg("客户端:" + sok.RemoteEndPoint.ToString() + " 连接成功~~~~~~~~");
                listIP.Items.Add(sok.RemoteEndPoint.ToString());
                listIP.SelectedItem = sok.RemoteEndPoint.ToString();
                //ParameterizedThreadStart p = new ParameterizedThreadStart(RecMsg);
                Thread th = new Thread(RecMsg);
                th.IsBackground = true;
                th.Start(sok.RemoteEndPoint.ToString());
            }
        }

        private void RecMsg(object ip)
        {
            while (true)
            {
                byte[] buff = new byte[1024 * 1024 * 5];
                int count = sockets[ip.ToString()].Receive(buff);
                ShowMsg(sockets[ip.ToString()].RemoteEndPoint.ToString() + "说:" + System.Text.Encoding.Default.GetString(buff, 0, count));
            }
        }

        private void ShowMsg(string msg)
        {
            txtmsg.Text += msg + "\r\n";
        }
        /// 
        /// 发送消息的方法
        /// 

        /// 
        private void sendMsg(string msg)
        {
            Socket s = sockets[listIP.SelectedItem.ToString()];
            ShowMsg("服务器对" + s.LocalEndPoint.ToString() + "说:" + msg);
            s.Send(System.Text.Encoding.Default.GetBytes(msg));
            txtSend.Text = "";
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            string msg = txtSend.Text.Trim();
            sendMsg(msg);
        }


    }

回答2:

了解下TCP/IP SOCKET 编程,实现这个程序不是很困难