这篇文章给大家分享的是有关如何使用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),,本文简单介绍一下同步通信及案例

聊天室案例 服务端

usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Windows.Forms;usingSystem.Net;usingSystem.Net.Sockets;usingSystem.Threading;namespace服务器{publicpartialclassForm1:Form{publicForm1(){InitializeComponent();//在多线程编程中,如果需要使用大到主线程需要进行检查取消CheckForIllegalCrossThreadCalls=false;}IDictionary<string,Socket>clientList=newDictionary<string,Socket>();privatevoidbutton1_Click(objectsender,EventArgse){Threadth=newThread(StartSever);th.IsBackground=true;th.Start();}voidStartSever(){//1.创建服务器端电话Socketserver=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.IP);//2.创建手机卡IPAddressip=IPAddress.Parse(txtIP.Text);//把ip和端口转化为IPEndPoint实例IPEndPointendpoint=newIPEndPoint(ip,int.Parse(txtPort.Text));//3.将电话卡插入到电话中,绑定端口server.Bind(endpoint);//4.开始监听电话server.Listen(20);listMsg.Items.Add("服务器已成功开启");//5.等待接电话while(true){//接收接入的一个客户端SocketconnectClient=server.Accept();if(connectClient!=null){stringinfor=connectClient.RemoteEndPoint.ToString();clientList.Add(infor,connectClient);listMsg.Items.Add(infor+"加入服务器");stringmsg=infor+"已成功进入聊天室";SendMsg(msg);Threadthread=newThread(ReciveMsg);thread.IsBackground=true;thread.Start(connectClient);}}}voidReciveMsg(objecto){Socketclient=oasSocket;while(true){try{byte[]arrMsg=newbyte[1024*1024];intlength=client.Receive(arrMsg);if(length>0){stringrecMsg=Encoding.UTF8.GetString(arrMsg,0,length);IPEndPointendpoint=client.RemoteEndPointasIPEndPoint;listMsg.Items.Add(DateTime.Now+"["+endpoint.Port.ToString()+"]"+recMsg);SendMsg("["+endpoint.Port.ToString()+"]"+recMsg);}}catch(Exception){client.Close();clientList.Remove(client.RemoteEndPoint.ToString());}}}privatevoidlabel1_Click(objectsender,EventArgse){stringip=IPAddress.Any.ToString();txtIP.Text=ip;}voidSendMsg(stringstr){foreach(variteminclientList){byte[]arrMsg=Encoding.UTF8.GetBytes(str);item.Value.Send(arrMsg);}}privatevoidbutton2_Click(objectsender,EventArgse){if(txtMsg.Text!=""){SendMsg(txtMsg.Text);}}}}

客户端

usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Windows.Forms;usingSystem.Net;usingSystem.Net.Sockets;usingSystem.Threading;namespace服务器2._12{publicpartialclassForm1:Form{publicForm1(){InitializeComponent();CheckForIllegalCrossThreadCalls=false;}SocketClient;privatevoidbutton1_Click(objectsender,EventArgse){//创建服务器端电话Client=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.IP);//创建手机卡IPAddressip=IPAddress.Parse(txtIP.Text);IPEndPointendinput=newIPEndPoint(ip,int.Parse(txtport.Text));Client.Connect(endinput);Threadth=newThread(ReciveMsg);th.IsBackground=true;th.Start(Client);}voidReciveMsg(objecto){Socketclient=oasSocket;//5.等待接电话while(true){byte[]arrlist=newbyte[1024*1024];intlength=client.Receive(arrlist);stringmsg=DateTime.Now+Encoding.UTF8.GetString(arrlist,0,length);listmsg.Items.Add(msg);}}privatevoidbutton2_Click(objectsender,EventArgse){if(txtinput.Text!=null){SendMsg(txtinput.Text);}}voidSendMsg(stringmsg){byte[]arrMsg=Encoding.UTF8.GetBytes(msg);Client.Send(arrMsg);}}}

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