温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何使用C#基于Socket的TCP通信实现聊天室

发布时间:2022-02-14 09:42:01 来源:亿速云 阅读:139 作者:小新 栏目:开发技术

这篇文章给大家分享的是有关如何使用C#基于Socket的TCP通信实现聊天室的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

具体内容如下

一.Socket(套接字)通信概念

套接字(socket)是通信的基石,用于描述IP地址和端口,是一个通信链的句柄,可以用来实现不同虚拟机或不同计算机之间的通信,是支持TCP/IP协议的网络通信的基本操作单元。它是网络通信过程中端点的抽象表示,包含进行网络通信必须的五种信息:连接使用的协议,本地主机的IP地址,本地进程的协议端口,远地主机的IP地址,远地进程的协议端口。

应用层通过传输层进行数据通信时,TCP会遇到同时为多个应用程序进程提供并发服务的问题。多个TCP连接或多个应用程序进程可能需要通过同一个 TCP协议端口传输数据。为了区别不同的应用程序进程和连接,许多计算机操作系统为应用程序与TCP/IP协议交互提供了套接字(Socket)接口。应 用层可以和传输层通过Socket接口,区分来自不同应用程序进程或网络连接的通信,实现数据传输的并发服务。

二、建立socket连接

建立Socket连接至少需要一对套接字,其中一个运行于客户端,称为ClientSocket ,另一个运行于服务器端,称为ServerSocket 。

套接字之间的连接过程分为三个步骤:服务器监听,客户端请求,连接确认

1、服务器监听:服务器端套接字并不定位具体的客户端套接字,而是处于等待连接的状态,实时监控网络状态,等待客户端的连接请求 

2、客户端请求:指客户端的套接字提出连接请求,要连接的目标是服务器端的套接字。为此,客户端的套接字必须首先描述它要连接的服务器的套接字,指出服务器端套接字的地址和端口号,然后就向服务器端套接字提出连接请求。

3、连接确认:当服务器端套接字监听到或者说接收到客户端套接字的连接请求时,就响应客户端套接字的请求,建立一个新的线程,把服务器端套接字的描述发给客户 端,一旦客户端确认了此描述,双方就正式建立连接。而服务器端套接字继续处于监听状态,继续接收其他客户端套接字的连接请求。

三、SOCKET连接与TCP连接

创建Socket连接时,可以指定使用的传输层协议,Socket可以支持不同的传输层协议(TCP或UDP),当使用TCP协议进行连接时,该Socket连接就是一个TCP连接。

socket通信:分为同步和异步通信,通信两端分别为客户端(Client)和服务器(Server),,本文简单介绍一下同步通信及案例

聊天室案例 服务端

如何使用C#基于Socket的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.Net.Sockets;
using System.Threading;
 
namespace 服务器
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            //在多线程编程中,如果需要使用大到主线程需要进行检查取消
            CheckForIllegalCrossThreadCalls = false;
        }
        IDictionary<string, Socket> clientList = new Dictionary<string, Socket>();
       
        private void button1_Click(object sender, EventArgs e)
        {
            Thread th = new Thread(StartSever);
            th.IsBackground = true;
            th.Start();
        }
        void StartSever()
        {
            //1.创建服务器端电话
            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            //2.创建手机卡
            IPAddress ip = IPAddress.Parse(txtIP.Text);
            //把ip和端口转化为IPEndPoint实例
            IPEndPoint endpoint = new IPEndPoint(ip, int.Parse(txtPort.Text));
            //3.将电话卡插入到电话中,绑定端口
            server.Bind(endpoint);
            //4.开始监听电话
            server.Listen(20);
            listMsg.Items.Add("服务器已成功开启");
            //5.等待接电话
            while (true)
            {
                //接收接入的一个客户端
                Socket connectClient = server.Accept();
                if (connectClient != null)
                {
                    string infor = connectClient.RemoteEndPoint.ToString();
                    clientList.Add(infor, connectClient);
                    listMsg.Items.Add(infor + "加入服务器");
                    string msg =infor+"已成功进入聊天室";
                    SendMsg(msg);
                    Thread thread = new Thread(ReciveMsg);
                    thread.IsBackground = true;
                    thread.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;
                        listMsg.Items.Add(DateTime.Now + "[" + endpoint.Port.ToString() + "]" + recMsg);
                        SendMsg("[" + endpoint.Port.ToString() + "]" + recMsg);
                    }
                }
                catch (Exception)
                {
                    client.Close();
                    clientList.Remove(client.RemoteEndPoint.ToString());
                }
            }
        }
        private void label1_Click(object sender, EventArgs e)
        {
            string ip = IPAddress.Any.ToString();
            txtIP.Text = ip;
        }
        void SendMsg(string str)
        {
            foreach (var item in clientList)
            {
                byte[] arrMsg = Encoding.UTF8.GetBytes(str);
                item.Value.Send(arrMsg);
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            if (txtMsg.Text!="")
            {
                SendMsg(txtMsg.Text);
            }
        }
    }
}

客户端 

如何使用C#基于Socket的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.Net.Sockets;
using System.Threading;
namespace 服务器2._12
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
        }
        Socket Client;
        private void button1_Click(object sender, EventArgs e)
        {
            //创建服务器端电话
            Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            //创建手机卡
            IPAddress ip = IPAddress.Parse(txtIP.Text);
            IPEndPoint endinput = new IPEndPoint(ip, int.Parse(txtport.Text));
            Client.Connect(endinput);
            Thread th = new Thread(ReciveMsg);
            th.IsBackground = true;
            th.Start(Client);
        }
        void ReciveMsg(object o)
        {
            Socket client = o as Socket;
            //5.等待接电话
            while (true)
            {
                byte[] arrlist = new byte[1024*1024];
                int length = client.Receive(arrlist);
                string msg = DateTime.Now + Encoding.UTF8.GetString(arrlist,0,length);
                listmsg.Items.Add(msg);
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            if (txtinput.Text!=null)
            {
                SendMsg(txtinput.Text);
            }
        }
        void SendMsg(string msg)
        {
            byte[] arrMsg = Encoding.UTF8.GetBytes(msg);
            Client.Send(arrMsg);
        }
    }
}

感谢各位的阅读!关于“如何使用C#基于Socket的TCP通信实现聊天室”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI