c# Tcp服务端与客户端通讯

这是服务端的代码
在这里插入图片描述

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

namespace TcpServer
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            //在多线程编程中,如果子线程需要使用主线程中创建的对象
            CheckForIllegalCrossThreadCalls = false;
        }

        Dictionary<string, Socket> clientList = new Dictionary<string, Socket>();
        private void Setserver()
        {
            //1.创建服务器端电话
            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            //2.创建手机卡
            IPAddress iP = IPAddress.Parse(textBox1.Text);
            IPEndPoint endPoint = new IPEndPoint(iP, int.Parse(textBox2.Text));
            //3.将电话卡插入到电话中
            server.Bind(endPoint);
            //4.开始监听电话
            //同一时刻允许同时加入链接的最大数量
            server.Listen(20);

            textBox3.Text = "服务器已经成功开启!\r\n" + textBox3.Text;

            //5.等待来电接电话
            while (true)
            {
                //接受接入的一个客户端
                connectClient = server.Accept();
                if (connectClient != null)
                {
                    string info = connectClient.RemoteEndPoint.ToString();
                    clientList.Add(info, connectClient);


                    textBox3.Text = info + "加入服务器!\r\n" + textBox3.Text;
                    string msg = DateTime.Now + "你已经成功进入聊天室!";
                    SendMsg(msg);
                    //每有一个客户端接入,需要有一个线程进行服务
                    Thread threadclient = new Thread(ReciveMsg);
                    threadclient.IsBackground = true;
                    //设置这个线程中的通信对象时对应的socket与客户端socket进行通信
                    threadclient.Start(connectClient);
                }
            }
        }
        void ReciveMsg(object o)
        {
            Socket client = o as Socket;
            while (true)
            {
                try
                {
                    byte[] arrMsg = new byte[1024 * 1024];
                    int length = client.Receive(arrMsg);
                    if (length > 0)
                    {
                        string recMsg = Encoding.UTF8.GetString(arrMsg, 0, length);
                        IPEndPoint endPoint = client.RemoteEndPoint as IPEndPoint;


                        textBox3.Text = DateTime.Now + "[" + endPoint.Port.ToString() + "]" + recMsg + "\r\n" + textBox3.Text;
                        SendMsg("[" + endPoint.Port.ToString() + "]" + recMsg);
                    }
                }
                catch (Exception)
                {
                    client.Close();
                    clientList.Remove(client.RemoteEndPoint.ToString());
                }
            }
        }
        Socket connectClient;
        void SendMsg(string str)
        {
            foreach (var item in clientList)
            {
                byte[] arrMsg = Encoding.UTF8.GetBytes(str);
                item.Value.Send(arrMsg);
            }
        }


        private void button1_Click(object sender, EventArgs e)
        {
            Thread thread = new Thread(Setserver);
            thread.IsBackground = true;
            thread.Start();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (textBox4.Text != null)
            {

                SendMsg(DateTime.Now + textBox4.Text);
                textBox4.Text = "";
            }
        }
    }
}

--------------------------------------------------------以下是客户端代码----------------------------------------------------------------

在这里插入图片描述


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

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

        Socket client;

        private void button2_Click(object sender, EventArgs e)
        {
            if (textBox4.Text != "")
            {
                SendMsg(textBox4.Text);
                textBox4.Text = "";
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);

            IPAddress ip = IPAddress.Parse(textBox1.Text);
            IPEndPoint endpoint = new IPEndPoint(ip, int.Parse(textBox2.Text));

            client.Connect(endpoint);

            Thread thread = new Thread(ReciveMsg);
            thread.IsBackground = true;
            thread.Start(client);
        }

        /// <summary>
        /// 接受数据
        /// </summary>
        /// <param name="o"></param>
        void ReciveMsg(object o)
        {
            client = o as Socket;
            while (true)
            {
                byte[] arrlist = new byte[1024 * 1024];
                int length = client.Receive(arrlist);
                string msg = DateTime.Now + Encoding.UTF8.GetString(arrlist, 0, length);

                textBox3.Text = msg + "\r\n" + textBox3.Text;
              
            }
        }

        void SendMsg(string msg)
        {
            byte[] arrmsg = Encoding.UTF8.GetBytes(msg);
            client.Send(arrmsg);
        }
    }
}

最终结果

在这里插入图片描述

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

糖朝

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值