c# 求符合要求的 TCP 、多线程、服务器 <> 客户端 通信代码

2025-05-19 23:54:03
推荐回答(3个)
回答1:

这个我正好做过,把代码给出粘过来吧,记得把分给我.  (后边有图片的)

服务器端程序:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading;

using System.Net;

using System.Net.Sockets;

using System.Windows.Forms;

namespace WindowsFormsApplication2

{

    public partial class Form1 : Form

    {

        private static TcpListener listener;

        private static Socket clientsocket;

        private static IPEndPoint listenPort;

        private static Thread clientservice;        

        delegate void setTextSring(string str);

        public Form1()

        {

            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)

        {

            string port = textBox1.Text;            

            if (port == "")

            {

                MessageBox.Show("请输入监听端口");

                return;

            }

            try

            {

                if (Int32.Parse(port) > 0)

                {                    

                    listenPort = new IPEndPoint(IPAddress.Any, Int32.Parse(port));

                    Thread thr = new Thread(new ThreadStart(StartListening));

                    thr.Start();

                }

                else

                    MessageBox.Show("监听端口号必须大于0,建议使用大于1024的端口");

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.Message);

            }

        }

        private void StartListening()

        {

            listener = new TcpListener(listenPort);

            SetText("IP: " + Convert.ToString(listenPort) + "\r\n");

            listener.Start();

            MessageBox.Show("服务已启动。。。");

            while (true)

            {

                try

                {

                    Socket s = listener.AcceptSocket();

                    clientsocket = s;

                    clientservice = new Thread(new ThreadStart(ServiceClient));

                    clientservice.Start();

                }

                catch (Exception e)

                {

                    MessageBox.Show(e.ToString());

                }

            }

        }

        private void SetText(string str)

        {

            if (textBox2.InvokeRequired)

            {

                setTextSring sts = new setTextSring(SetText);

                Invoke(sts, new object[] { str });

            }

            else

            {

                this.textBox2.Text += str;

            }

        }

        public static string byteToHexStr(byte[] bytes)

        {

            string returnStr = "";

            if (bytes != null)

            {

                for (int i = 0; i < bytes.Length; i++)

                {

                    returnStr += bytes[i].ToString("X2") + " ";

                }

            }

            return returnStr;

        }

        private void ServiceClient()

        {

            Socket client = clientsocket;

            bool keepalive = true;

            while (keepalive)

            {

                byte[] buffer = new Byte[60];

                client.Receive(buffer);                

                string clientcommand = byteToHexStr(buffer);

                clientcommand += "\r\n";                

                SetText(clientcommand);

            }

        }

        private static void SendToClient(Socket cli, string str)

        {

            Byte[] sendbytes = System.Text.Encoding.UTF8.GetBytes(str.ToCharArray());

            cli.Send(sendbytes);

        }

   }

}

客户端程序:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.Net;

using System.Net.Sockets;

using System.Threading;

using System.IO;

namespace WindowsFormsApplication3

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

        private TcpClient clientsocket;

        private NetworkStream ns;

        private StreamReader sr;

        private bool bConn = false;

        private string clientname = "";

        private Thread t;

        private void button2_Click(object sender, EventArgs e)

        {

            string ip = textBox1.Text;

            int port = Int32.Parse(textBox2.Text);

            if (port > 0)

            {

                if (!EstablishConnection(ip, port))

                    return;

            }

            else

            {

                MessageBox.Show("duankouhaodayu0");

                return;

            }

            t = new Thread(new ThreadStart(recivechat));

            t.Start();

            MessageBox.Show("连接成功!");

        }

        private bool EstablishConnection(string IP, int port)

        {

            try

            {

                clientsocket = new TcpClient(IP, port);

                ns = clientsocket.GetStream();

                sr = new StreamReader(ns);

                bConn = true;

                return true;

            }

            catch (Exception e) 

            {

               MessageBox.Show(e.ToString());               

            }

            return false;

        }

        private void recivechat()

        {

            bool keeplive = true;

            while (keeplive)

            {

                try

                {

                    Byte[] buffer = new Byte[2048];

                    ns.Read(buffer, 0, buffer.Length);

                    string chatter = System.Text.Encoding.UTF8.GetString(buffer);

                    textBox4.Text += chatter;

                }

                catch (Exception e)

                {

                    MessageBox.Show(e.ToString());

                }

            }

        }

        private void button1_Click(object sender, EventArgs e)

        {

            string msg = textBox3.Text;

            Byte[] outbytes = System.Text.Encoding.UTF8.GetBytes(msg.ToCharArray());

            ns.Write(outbytes, 0, outbytes.Length);

            MessageBox.Show("发送成功!");

        }

    }

我把程序的界面图片给你,你参考下

回答2:

有现成的类似QQ的源代码
一个服务器,多个客户端可以连接,要就hi我,我一直在线

回答3:

我有一个类似的案例,你的邮箱

我的邮箱是 yinzuo1988@163.com

晚上发给你,在宿舍里。。。