首页 > 分享 > C#socket通信(服务器端与客户端实现简单的聊天室通信)

C#socket通信(服务器端与客户端实现简单的聊天室通信)

知识基础:
1.按网络覆盖范围,计算机网络可分类为广域网、城域网、局域网和Internet。
2.在TCP/IP网络中测试连通性的常用命令是Ping 命令,ipconfig。
3.Internet的核心协议是TCP/IP 。
4.IP地址127.0.0.1是一个测试地址。
5.Internet的前身是Arpanet 。
6.在企业内部网与外部网之间,用来检查网络请求分组是否合法,保护网络资源不被非法使用的技术是防火墙技术。
7.设置防火墙的主要目的是防止局域网外部的非法访问。
8.防火墙:防火墙(Firewall),也称防护墙,它是一种位于内部网络与外部网络之间的网络安全系统。一项信息安全的防护系统,依照特定的规则,允许或是限制传输的数据通过。

socket通信
①:创建一个用于监听连接的Socket对象;
②:用指定的端口号和服务器的Ip建立一个EndPoint对象;
③:用Socket对象的Bind()方法绑定EndPoint;
④:用Socket对象的Listen()方法开始监听;
⑤:接收到客户端的连接,用Socket对象的Accept()方法创建一个新的用于和客户端进行通信的Socket对象;
⑥:通信结束后一定记得关闭Socket。

服务器端

å¨è¿éæå¥å¾çæè¿°

namespace 服务器

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

///多线程编程中,如果子线程需要使用主线程中创建的对象和控件,最好在主线程中体现进行检查取消

CheckForIllegalCrossThreadCalls = false;

}

/// <summary>

/// 创建一个字典,用来存储记录服务器与客户端之间的连接(线程问题)

/// </summary>

Dictionary<string, Socket> clientList = new Dictionary<string, Socket>();

/// <summary>

/// 创建连接

/// </summary>

private void button1_Click(object sender, EventArgs e)

{

Thread myServer = new Thread(MySocket);

//设置这个线程是后台线程

myServer.IsBackground = true;

myServer.Start();

}

/// <summary>

/// 创建连接的方法

/// </summary>

void MySocket()

{

//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);

listBox1.Items.Add("服务器已经成功开启!");

//5.等待来电接电话

while (true)

{

//接受接入的一个客户端

Socket connectClient = server.Accept();

if (connectClient != null)

{

string infor = connectClient.RemoteEndPoint.ToString();

clientList.Add(infor, connectClient);

listBox1.Items.Add(infor + "加入服务器!");

///服务器将消息发送至客服端

string msg = infor + "已成功进入到聊天室!";

SendMsg(msg);

//每有一个客户端接入时,需要有一个线程进行服务

Thread threadClient = new Thread(ReciveMsg);

threadClient.IsBackground = true;

//设置这个线程中的通信对象是对应的Socket和客户端Socket进行通信

threadClient.Start(connectClient);

}

}

}

/// <summary>

/// 服务器接收到客户端发送的消息

/// </summary>

/// <param name="o">客户端</param>

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;

//服务器显示客户端的端口号和消息

listBox1.Items.Add(DateTime.Now + "[" + endPoint.Port.ToString() + "]:" + recMsg);

//服务器发送接收到的客户端信息给客户端

SendMsg("[" + endPoint.Port.ToString() + "]:" + recMsg);

}

}

catch (Exception)

{

///关闭客户端

client.Close();

///移除添加在字典中的服务器和客户端之间的线程

clientList.Remove(client.RemoteEndPoint.ToString());

}

}

}

/// <summary>

/// 获取本地IP

/// </summary>

private void label1_Click(object sender, EventArgs e)

{

string ip = IPAddress.Any.ToString();

textBox1.Text = ip;

}

/// <summary>

/// 服务器发送消息,客户端接收到

/// </summary>

void SendMsg(string str)

{

///遍历出字典中的所有线程

foreach (var item in clientList)

{

byte[] arrMsg = Encoding.UTF8.GetBytes(str);

///获取键值,发送消息

item.Value.Send(arrMsg);

}

}

/// <summary>

/// 服务器发送消息

/// </summary>

private void button2_Click(object sender, EventArgs e)

{

if (textBox3.Text != "")

{

SendMsg(textBox3.Text);

textBox3.Text = "";

}

}

}

}

å¨è¿éæå¥å¾çæè¿°

namespace 客户端

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

CheckForIllegalCrossThreadCalls = false;

}

/// <summary>

/// 创建客户端

/// </summary>

Socket client;

private void button1_Click(object sender, EventArgs e)

{

///创建客户端

client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);

///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)

{

Socket client = o as Socket;

while (true)

{

try

{

///定义客户端接收到的信息大小

byte[] arrList = new byte[1024 * 1024];

///接收到的信息大小(所占字节数)

int length = client.Receive(arrList);

string msg = DateTime.Now + Encoding.UTF8.GetString(arrList, 0, length);

listBox1.Items.Add(msg);

}

catch (Exception)

{

///关闭客户端

client.Close();

}

}

}

/// <summary>

/// 客户端发送消息给服务端

/// </summary>

private void button2_Click(object sender, EventArgs e)

{

if (textBox3.Text!="")

{

SendMsg(textBox3.Text);

}

}

/// <summary>

/// 客户端发送消息,服务端接收到

/// </summary>

void SendMsg(string str)

{

byte[] arrMsg = Encoding.UTF8.GetBytes(str);

client.Send(arrMsg);

}

}

}

相关知识

一种基于J2ME的移动支付系统的设计与实现...
java(eclipse)与VC++6.0 UDP通信
unity csharp socket 异步通信 客户端 作者:围城(solq)
通信与信息工程学院举办2024
基于Android的水稻病虫害图像的识别与诊断系统
实现农业作业精准化智能化!移远通信推出北斗导航农机自驾系统
智能综合安防监控系统的设计与实现
【免费】我自己写的网络聊天系统资源
【QT教程】QT6 Web开发入门 QT Web
《植物学通信》读书报告

网址: C#socket通信(服务器端与客户端实现简单的聊天室通信) https://m.huajiangbk.com/newsview948569.html

所属分类:花卉
上一篇: spring security安
下一篇: Tomcat安全加固与防护实践(