c#基于WinForm的Socket实现简单的聊天室 IM
作者:天天向上518 发布时间:2021-11-27 04:47:57
标签:c#,WinForm,聊天室,socket,IM
1:什么是Socket
所谓套接字(Socket),就是对网络中不同主机上的应用进程之间进行双向通信的端点的抽象。
一个套接字就是网络上进程通信的一端,提供了应用层进程利用网络协议交换数据的机制。
从所处的地位来讲,套接字上联应用进程,下联网络协议栈,是应用程序通过网络协议进行通信的接口,是应用程序与网络协议根进行交互的接口。
2:客服端和服务端的通信简单流程
3:服务端Code:
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;
namespace ChartService
{
using System.Net;
using System.Net.Sockets;
using System.Threading;
using ChatCommoms;
using ChatModels;
public partial class ServiceForm : Form
{
Socket _socket;
private static List<ChatUserInfo> userinfo = new List<ChatUserInfo>();
public ServiceForm()
{
InitializeComponent();
}
private void btnServicStart_Click(object sender, EventArgs e)
{
try
{
string ip = textBox_ip.Text.Trim();
string port = textBox_port.Text.Trim();
if (string.IsNullOrWhiteSpace(ip) || string.IsNullOrWhiteSpace(port))
{
MessageBox.Show("IP与端口不可以为空!");
}
ServiceStartAccept(ip, int.Parse(port));
}
catch (Exception)
{
MessageBox.Show("连接失败!或者ip,端口参数异常");
}
}
public void ServiceStartAccept(string ip, int port)
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint endport = new IPEndPoint(IPAddress.Parse(ip), port);
socket.Bind(endport);
socket.Listen(10);
Thread thread = new Thread(Recevice);
thread.IsBackground = true;
thread.Start(socket);
textboMsg.AppendText("服务开启ok...");
}
/// <summary>
/// 开启接听服务
/// </summary>
/// <param name="obj"></param>
private void Recevice(object obj)
{
var socket = obj as Socket;
while (true)
{
string remoteEpInfo = string.Empty;
try
{
Socket txSocket = socket.Accept();
_socket = txSocket;
if (txSocket.Connected)
{
remoteEpInfo = txSocket.RemoteEndPoint.ToString();
textboMsg.AppendText($"\r\n{remoteEpInfo}:连接上线了...");
var clientUser = new ChatUserInfo
{
UserID = Guid.NewGuid().ToString(),
ChatUid = remoteEpInfo,
ChatSocket = txSocket
};
userinfo.Add(clientUser);
listBoxCoustomerList.Items.Add(new ChatUserInfoBase { UserID = clientUser.UserID, ChatUid = clientUser.ChatUid });
listBoxCoustomerList.DisplayMember = "ChatUid";
listBoxCoustomerList.ValueMember = "UserID";
ReceseMsgGoing(txSocket, remoteEpInfo);
}
else
{
if (userinfo.Count > 0)
{
userinfo.Remove(userinfo.Where(c => c.ChatUid == remoteEpInfo).FirstOrDefault());
//移除下拉框对于的socket或者叫用户
}
break;
}
}
catch (Exception)
{
if (userinfo.Count > 0)
{
userinfo.Remove(userinfo.Where(c => c.ChatUid == remoteEpInfo).FirstOrDefault());
//移除下拉框对于的socket或者叫用户
}
}
}
}
/// <summary>
/// 接受来自客服端发来的消息
/// </summary>
/// <param name="txSocket"></param>
/// <param name="remoteEpInfo"></param>
private void ReceseMsgGoing(Socket txSocket, string remoteEpInfo)
{
//退到一个客服端的时候 int getlength = txSocket.Receive(recesiveByte); 有抛异常
Thread thread = new Thread(() =>
{
while (true)
{
try
{
byte[] recesiveByte = new byte[1024 * 1024 * 4];
int getlength = txSocket.Receive(recesiveByte);
if (getlength <= 0) { break; }
var getType = recesiveByte[0].ToString();
string getmsg = Encoding.UTF8.GetString(recesiveByte, 1, getlength - 1);
ShowMsg(remoteEpInfo, getType, getmsg);
}
catch (Exception)
{
//string userid = userinfo.FirstOrDefault(c => c.ChatUid == remoteEpInfo)?.ChatUid;
listBoxCoustomerList.Items.Remove(remoteEpInfo);
userinfo.Remove(userinfo.FirstOrDefault(c => c.ChatUid == remoteEpInfo));//从集合中移除断开的socket
listBoxCoustomerList.DataSource = userinfo;//重新绑定下来的信息
listBoxCoustomerList.DisplayMember = "ChatUid";
listBoxCoustomerList.ValueMember = "UserID";
txSocket.Dispose();
txSocket.Close();
}
}
});
thread.IsBackground = true;
thread.Start();
}
private void ShowMsg(string remoteEpInfo, string getType, string getmsg)
{
textboMsg.AppendText($"\r\n{remoteEpInfo}:消息类型:{getType}:{getmsg}");
}
private void Form1_Load(object sender, EventArgs e)
{
CheckForIllegalCrossThreadCalls = false;
this.textBox_ip.Text = "192.168.1.101";//初始值
this.textBox_port.Text = "50000";
}
/// <summary>
/// 服务器发送消息,可以先选择要发送的一个用户
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSendMsg_Click(object sender, EventArgs e)
{
var getmSg = textBoxSendMsg.Text.Trim();
if (string.IsNullOrWhiteSpace(getmSg))
{
MessageBox.Show("要发送的消息不可以为空", "注意"); return;
}
var obj = listBoxCoustomerList.SelectedItem;
int getindex = listBoxCoustomerList.SelectedIndex;
if (obj == null || getindex == -1)
{
MessageBox.Show("请先选择左侧用户的用户"); return;
}
var getChoseUser = obj as ChatUserInfoBase;
var sendMsg = ServiceSockertHelper.GetSendMsgByte(getmSg, ChatTypeInfoEnum.StringEnum);
userinfo.FirstOrDefault(c => c.ChatUid == getChoseUser.ChatUid)?.ChatSocket?.Send(sendMsg);
}
/// <summary>
/// 给所有登录的用户发送消息,群发了
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
var getmSg = textBoxSendMsg.Text.Trim();
if (string.IsNullOrWhiteSpace(getmSg))
{
MessageBox.Show("要发送的消息不可以为空", "注意"); return;
}
if (userinfo.Count <= 0)
{
MessageBox.Show("暂时没有客服端登录!"); return;
}
var sendMsg = ServiceSockertHelper.GetSendMsgByte(getmSg, ChatTypeInfoEnum.StringEnum);
foreach (var usersocket in userinfo)
{
usersocket.ChatSocket?.Send(sendMsg);
}
}
/// <summary>
/// 服务器给发送震动
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSendSnak_Click(object sender, EventArgs e)
{
var obj = listBoxCoustomerList.SelectedItem;
int getindex = listBoxCoustomerList.SelectedIndex;
if (obj == null || getindex == -1)
{
MessageBox.Show("请先选择左侧用户的用户"); return;
}
var getChoseUser = obj as ChatUserInfoBase;
byte[] sendMsgByte = ServiceSockertHelper.GetSendMsgByte("", ChatTypeInfoEnum.Snake);
userinfo.FirstOrDefault(c => c.ChatUid == getChoseUser.ChatUid)?.ChatSocket.Send(sendMsgByte);
}
}
}
4:客服端Code:
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;
namespace ChatClient
{
using ChatCommoms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
CheckForIllegalCrossThreadCalls = false;
this.textBoxIp.Text = "192.168.1.101";//先初始化一个默认的ip等
this.textBoxPort.Text = "50000";
}
Socket clientSocket;
/// <summary>
/// 客服端连接到服务器
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnServicStart_Click(object sender, EventArgs e)
{
try
{
var ipstr = textBoxIp.Text.Trim();
var portstr = textBoxPort.Text.Trim();
if (string.IsNullOrWhiteSpace(ipstr) || string.IsNullOrWhiteSpace(portstr))
{
MessageBox.Show("要连接的服务器ip和端口都不可以为空!");
return;
}
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientSocket.Connect(IPAddress.Parse(ipstr), int.Parse(portstr));
labelStatus.Text = "连接到服务器成功...!";
ReseviceMsg(clientSocket);
}
catch (Exception)
{
MessageBox.Show("请检查要连接的服务器的参数");
}
}
private void ReseviceMsg(Socket clientSocket)
{
Thread thread = new Thread(() =>
{
while (true)
{
try
{
Byte[] byteContainer = new Byte[1024 * 1024 * 4];
int getlength = clientSocket.Receive(byteContainer);
if (getlength <= 0)
{
break;
}
var getType = byteContainer[0].ToString();
string getmsg = Encoding.UTF8.GetString(byteContainer, 1, getlength - 1);
GetMsgFomServer(getType, getmsg);
}
catch (Exception ex)
{
}
}
});
thread.IsBackground = true;
thread.Start();
}
private void GetMsgFomServer(string strType, string msg)
{
this.textboMsg.AppendText($"\r\n类型:{strType};{msg}");
}
/// <summary>
/// 文字消息的发送
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSendMsg_Click(object sender, EventArgs e)
{
var msg = textBoxSendMsg.Text.Trim();
var sendMsg = ServiceSockertHelper.GetSendMsgByte(msg, ChatModels.ChatTypeInfoEnum.StringEnum);
int sendMsgLength = clientSocket.Send(sendMsg);
}
}
}
5:测试效果:
6:完整Code GitHUb下载路径
https://github.com/zrf518/WinformSocketChat.git
7:这个只是一个简单的聊天练习Demo,待进一步完善(实现部分功能,传递的消息byte[0]为消息的类型,用来判断是文字,还是图片等等),欢迎大家指教
来源:https://www.cnblogs.com/Fengge518/p/14536940.html


猜你喜欢
- 本文实例为大家分享了Android使用SoundPool播放音效的具体代码,供大家参考,具体内容如下SoundPool(int maxStr
- Ireport的安装及使用一、 安装ireport1.点击安装包,可以一直点击下一步,安装完成。2.安装完成后,要在如下安装目录下添加ojd
- file.mkdir()创建单级文件夹,file.mkdirs()创建多级文件夹,file.createNewFile()创建的是一个文件。
- 本文实例分析了C#中Convert.ToString和ToString的区别,对于初学者来说是很有必要加以熟练掌握的。具体分析如下:1.Co
- 1 使用阿里的FastJson1.1 项目的pom.xml依赖<dependency> <groupId>com.a
- IDEA版本:2020.3具体步骤一、开启IDEA的自动编译【静态】1.File->Settings。2.直接搜索Compiler,选
- 对网页中各种不同格式的发布时间进行抽取,将发布时间以规整的“yyyy-MM-dd HH:mm:ss”格式表示出来,只能尽量追求精确,但是因为
- 工欲善其事,必先利其器,对于想要深入学习Android源码,必须先掌握Android编译命令.一、引言关于Android Build系统,这
- 本文实例为大家分享了Java模拟实现斗地主发牌的具体代码,供大家参考,具体内容如下题目:模拟斗地主的发牌实现,54张牌,每张牌不同的花色(红
- 本文简单分析了C/C++中常用函数的易错点,包括memset、sizeof、getchar等函数。分享给大家供大家参考之用。具体分析如下:1
- 让我们来看看这段代码: import java.util.BitSet;import java.util.concurrent.C
- 目录1.C语音的字符串有两种1.1字符数组1.2字符指针2.字符串常用的方法2.1strcpy字符串拼接2.2strchr字符串中查找字符2
- RoomRoom主要分三个部分 database、dao和实体类entityEntityentity实体类定义时需要用到@Entity(ta
- 微软官方的MSDN上说async和await是“异步”,但是不少人(包括笔者自己)都有一些误区需要澄清:为什么await语句之后没有执行?不
- 接口:红色;实现类:黑色字体一、 Collection集合 Collection |_____Set(HashSet)&
- 提示:IntelliJ IDEA以下简称IDEA;####IntelliJ IDEA 配置git:需要的材料:一、git.exe二、配置gi
- 基本要点1、定义根据百度百科的定义,RESTFUL是一种网络应用程序的设计风格和开发方式2、传统方式与Restful风格的区别在我们学习re
- 这篇文章主要介绍了JavaWeb项目Servlet无法访问问题解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价
- 文章描述跑马灯效果,功能效果大家应该都知道,就是当我们的文字过长,整个页面放不下的时候(一般用于公告等),可以让它自动实现来回滚动,以让客户
- 一、前言WPF没有内置IP地址输入控件,因此我们需要通过自己定义实现。我们先看一下IP地址输入控件有什么特性:输满三个数字焦点会往右移键盘←