首页 > 编程语言 >C# 聊天室(基于TCP协议)

C# 聊天室(基于TCP协议)

时间:2023-05-08 18:25:06浏览次数:40  
标签:聊天室 socket C# System TCP receiveSocket ex using ShowMessage

客户端和服务端

客户端

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

namespace Client
{
    public partial class Form1 : Form
    {
        Socket socket = null;
        public Form1()
        {
            InitializeComponent();



            btnConnect.Click += BtnConnect_Click;
            btnSend.Click += BtnSend_Click;
            Task.Run(Receive);
        }
        private void Receive()
        {
            while (true)
            {
                if (socket == null) continue;
                if (!socket.Connected) continue;

                try
                {
                    byte[] buffer = new byte[1024];
                    int len = socket.Receive(buffer);
                    if (len < 1) continue;

                    string msg = Encoding.UTF8.GetString(buffer, 0, len);
                    ShowMessage(msg + "\n");
                }
                catch (Exception ex)
                {
                    ShowMessage(ex.Message + "\n");
                    socket = null;
                }

            }

        }
        private void BtnSend_Click(object sender, EventArgs e)
        {
            if (!socket.Connected)
            {
                ShowMessage($"未连接,无法发送");
                return;
            }
            try
            {
                var buffer = Encoding.UTF8.GetBytes(rtxtSend.Text);
                socket.Send(buffer);
                ShowMessage($"成功发送到:{socket.RemoteEndPoint},消息:{rtxtSend.Text}");
            }
            catch (Exception ex)
            {

                ShowMessage($"发送失败:{socket.RemoteEndPoint},{ex.Message}");
                socket = null;
            }

        }

        private void BtnConnect_Click(object sender, EventArgs e)
        {
            if (socket != null && socket.Connected)
            {
                ShowMessage($"无需重复连接");
                return;
            }
            try
            {
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                ShowMessage($"LocalEndPoint={socket.LocalEndPoint},RemoteEndPoint={socket.RemoteEndPoint}");
                var ipEndPoint = new IPEndPoint(IPAddress.Parse(txtIP.Text), int.Parse(txtPort.Text));
                socket.Connect(ipEndPoint);

                if (socket.Connected)
                {
                    ShowMessage($"成功连接到:{socket.RemoteEndPoint}");
                }
            }
            catch (Exception ex)
            {
                ShowMessage($"连接失败:{ex.Message}");
                socket = null;
            }


        }
        private void ShowMessage(string msg)
        {
            //子线程调用
            if (rtxtLog.InvokeRequired)
            {
                rtxtLog.Invoke(new Action(() => rtxtLog.Text += msg + "\n"));
            }
            //主线程调用
            else
            {
                rtxtLog.Text += msg + "\n";
            }


        }
    }
}

服务端

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace Server
{
    class Program
    {
        static Socket socket = null;
        static void Main(string[] args)
        {
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            socket.Bind(new IPEndPoint(IPAddress.Parse("192.168.0.117"), 60000));
            socket.Listen(10);
            Console.WriteLine("已启动侦听");
            Task.Run(Connect);

            Console.ReadLine();

        }
        static List<Socket> socketPool = new List<Socket>();
       static Socket acceptSocket = null;
        static void Connect()
        {
            while (true)
            {
                try
                {
                    acceptSocket = socket.Accept();
                    var receiveSocket = acceptSocket;
                    Console.WriteLine($"已接受连接:{receiveSocket.RemoteEndPoint}");
                    socketPool.Add(receiveSocket);
                    Task.Run(Receive);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"连接失败:{ex.Message}");
                }

            }

        }

        static void Receive()
        {
            var receiveSocket = acceptSocket;
            while (true)
            {
                if (receiveSocket == null) continue;
                if (!receiveSocket.Connected) continue;
                try
                {
                    byte[] buffer = new byte[1024];
                    var len = receiveSocket.Receive(buffer);
                    if (len < 1) continue;
                    var msg = Encoding.UTF8.GetString(buffer, 0, len);
                    Console.WriteLine($"收到来自 {receiveSocket.RemoteEndPoint} 的消息 {msg}");

                    var responseBuffer = Encoding.UTF8.GetBytes($"服务器已收到{receiveSocket.RemoteEndPoint},消息:" + msg);
                    receiveSocket.Send(responseBuffer);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message+"\n");
                }
            

            }

        }

    }
}

 

标签:聊天室,socket,C#,System,TCP,receiveSocket,ex,using,ShowMessage
From: https://www.cnblogs.com/zhangdezhang/p/17382738.html

相关文章

  • c++打卡练习(22)
    判断一个数是不是完数流程图:伪代码:源代码:#include<iostream>usingnamespacestd;intmain(){ intN,i,j,S; cin>>N; for(i=2;i<=N;i++){ S=0; for(j=1;j<=(i/2);j++){ if(i%j==0){ S+=j; } if(S==i){ cout<<S<<""<<"is......
  • MVCC
    一多版本并发控制MVCC:SnapshotReadvsCurrentReadMySQLInnoDB存储引擎,实现的是基于多版本的并发控制协议——MVCC(Multi-VersionConcurrencyControl)(注:与MVCC相对的,是基于锁的并发控制,Lock-BasedConcurrencyControl)。MVCC最大的好处,相信也是耳熟能详:读不加锁,读......
  • CF920E Connected Components? 题解
    一道线段树优化建图好题(大雾扣掉一些边看起来不好做,我们直接大力加上存在的边,然后跑连通块。对于一个点,如果他被扣掉了\(k\)个邻居,那么没扣掉的那些形成了至多\(k+1\)个连续段,可以用线段树优化建图向每个连续段各用\(\log\)的代价连边。由于总共扣掉了\(m\)条边,所以总共......
  • MISRA C 2012标准学习与理解
    目录总览指示(Directives)实现编译和构建需求可追踪性代码设计规则(Rules)标准C环境未使用代码(Unusedcode)注释(Comments)字符集和词汇约定(Charactersetsandlexicalconventions)标识符类型(types)Literalsandconstants声明和定义(Declarationsanddefinitions)初始化(Initialization)......
  • PKUSC 2023
    不保证Subtask完全准确。题面与\(100\%\)数据范围大致准确。D1T1给定两个长度相同的字符串\(S[1\cdotsn],T[1\cdotsn]\),你需要对每个\(1\lei\len\)输出:如果将\(S_i\)替换为\(T_i\),得到的新字符串的border长度是多少。一个字符串\(S\)的border长度定义为......
  • 未提供与“Course.Course(string, int, int)”的所需参数“Name”对应的参数
    当传给类中的参数不确定有无时,则要给父类加个无参构造方法 ......
  • ChatGLM-6B本地化部署
    一、硬件要求量化等级最低GPU显存(推理)最低GPU显存(高效参数微调)FP16(无量化)13GB14GBINT88GB9GBINT46GB7GB二、环境要求需先安装git、python三、下载源码1mkdir/gpt2cdgpt3gitclonehttps://github.com/THUDM/ChatGLM-6B.git ......
  • 【Oracle】使用xmlagg(xmlparse(content()).getclobval()拼接信息
    使用xmlagg(xmlparse(content()).getclobval()拼接信息简单来说格式如下xmlagg(xmlparse(content(内容||分割符)).getclobval()内容就是使用显示的数据部分,分隔符不同效果不同,分隔符可以使用chr()函数无分隔符xmlagg(xmlparse(content('这是一个字段:'||v.supercode||'、......
  • WARNING: Running pip as the 'root' user can result in broken permissions and con
      pipinstall-rrequirements.txt报错"WARNING:Runningpipasthe'root'usercanresultinbrokenpermissionsandconflictingbehaviourwiththesystempackagemanager.Itisrecommendedtouseavirtualenvironmentinstead:https://pip.pyp......
  • 关于Curl命令的使用
    最常用的curl命令1、发送GET请求curlURL例:curlURL?a=1&b=nihao2、发送POST请求curl-XPOST-d'a=1&b=nihao'URL3、发送json格式请求curl-H"Content-Type:application/json"-XPOST-d'{"abc":123,"bcd":"nihao"}......