这篇文章主要为大家详细介绍了C#基于Socket实现多人聊天功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了C#基于Socket实现多人聊天功能的具体代码,供大家参考,具体内容如下
服务器
服务器负责接受所有客户端发来的消息,和将接受到的问题群发到其他用户。
代码:
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace ChatRoomService
{
class Service
{
Socket socketSevice ;
List<Socket> userList;//用户组
public Service()
{
socketSevice = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
userList = new List<Socket>();
}
public void Start()
{
socketSevice.Bind(new IPEndPoint(IPAddress.Any,5566));
socketSevice.Listen(10);
Console.WriteLine("服务器启动成功");
//开启接受连接,用多线程
Thread accThread = new Thread(Accept);
accThread.IsBackground = true;
accThread.Start();
}
private void Accept()
{
//接受连接
Socket clientSocket = socketSevice.Accept();
userList.Add(clientSocket);
//打印已经连接IP地址
Console.WriteLine(IPToAddress(clientSocket)+"连接进来了");
//
Thread RecvThread = new Thread(ReceMessage);
RecvThread.IsBackground = true;
RecvThread.Start(clientSocket);
Accept();//递归
}
//接收客户端信息
private void ReceMessage(Object obj)
{
Socket client = obj as Socket;
byte[] strByte = new byte[1024 * 1024];//设定接受字符的长度
string str = "";
try
{
int len = client.Receive(strByte);//接受用户发送的内容
str = Encoding.Default.GetString(strByte, 0, len);
Broadcast(str,client);//广播给用户
Console.WriteLine(str);
}
catch (Exception e)
{
Console.WriteLine(IPToAddress(client)+"退出");
userList.Remove(client);
Thread.CurrentThread.Abort();//退出时掐死线程,不然递归反弹
}
ReceMessage(client); //使用递归
}
/// <summary>
/// 广播信息
/// </summary>
/// <param name="useStr">传入收到的传输的内容</param>
/// <param name="obj">传送信息的客户</param>
private void Broadcast(string userStr,object obj)
{
Socket clientSend = obj as Socket; //当前发送信息的客户
foreach (Socket client in userList)
{
if (client != clientSend)//将信息广播给其他用户
{
client.Send(Encoding.Default.GetBytes(IPToAddress(clientSend)+":"+userStr));
}
}
} //转换出连来客户的IP地址
private string IPToAddress(Socket soket)
{
return (soket.RemoteEndPoint as IPEndPoint).Address.ToString();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ChatRoomService
{
class Program
{
static void Main(string[] args)
{
Service ss = new Service();
ss.Start();
Console.ReadLine();
}
}
}
客户端
客户端的功能开始十分简单,可以发送信息给服务器。也可以接收服务器转发过来其他客户端的信息。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ChatRoom
{
class ClientRoom
{
Socket clientSocket;
public ClientRoom()
{
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//初始化服务器
}
/// <summary>
/// 连接服务器
/// </summary>
/// <param name="Ip"></param>
/// <param name="port"></param>
public void Connected(string Ip,int port)
{
clientSocket.Connect(Ip,port);
Console.WriteLine("连接成功");
// ClientSocket.Bind(new IPEndPoint());
Thread RecvThread = new Thread(RecvMessage);
RecvThread.IsBackground = true;
RecvThread.Start();
}
public void Send(String str)
{
clientSocket.Send(Encoding.Default.GetBytes(str));
}
/// <summary>
/// 接受信息
/// </summary>
private void RecvMessage()
{
try
{
byte[] strByte = new byte[500 * 1024];
int len = clientSocket.Receive(strByte);
Console.WriteLine(Encoding.Default.GetString(strByte, 0, len));
}
catch (Exception e) //服务器关闭
{
Console.WriteLine("服务器关闭");
Thread.CurrentThread.Abort();//关闭时切断进程
}
RecvMessage();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ChatRoom
{
class Program
{
static void Main(string[] args)
{
ClientRoom client = new ClientRoom();
client.Connected("127.0.0.1", 5566);
string str = Console.ReadLine();
while (!str.Equals("q"))
{
client.Send(str);
str = Console.ReadLine();
}
Console.ReadLine();
}
}
}
可以正常对话,测试一下。假装和自己对话
目前还没有解决沾包问题
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持得得之家。
沃梦达教程
本文标题为:C#基于Socket实现多人聊天功能
基础教程推荐
猜你喜欢
- unity实现动态排行榜 2023-04-27
- C# List实现行转列的通用方案 2022-11-02
- C#控制台实现飞行棋小游戏 2023-04-22
- winform把Office转成PDF文件 2023-06-14
- ZooKeeper的安装及部署教程 2023-01-22
- C#类和结构详解 2023-05-30
- 一个读写csv文件的C#类 2022-11-06
- C# 调用WebService的方法 2023-03-09
- C# windows语音识别与朗读实例 2023-04-27
- linux – 如何在Debian Jessie中安装dotnet core sdk 2023-09-26