C# 控制台 使用 Socket实现客户端之间信息群发

Server端代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace Server_Tcp
{
class Server
{
private List<Socket> socketList;
private int socketIndex = 0;
private Socket socket; //服务器监听套接字
private bool isListen = true;//判断服务器是否在监听(目的是为了方便退出)
private bool isFriend = false;
public Server()
{
socketList= new List<Socket>();
//定义网络终结点(封装IP和端口)
IPEndPoint endPoint =new IPEndPoint(IPAddress.Parse("192.168.1.104"), 9999);
//实例化套接字(监听套接字)
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp);
//服务器端绑定地址
socket.Bind(endPoint);
//开始监听
socket.Listen(10);//10表示“监听对列”的最大长度
Console.WriteLine("服务器端已经启动");
try
{
while (isListen)
{
//Accept()接收客户端的连接
//会阻断当前线程的进行
Socket acceptSocket = socket.Accept();
Console.WriteLine("有一个客户端连接。。。。。。");
socketList.Add(acceptSocket);

//开启一个后台线程,进行客户端的会话
Thread clientMsg = new Thread(ClientMsg);
clientMsg.IsBackground = true;//设置为后台线程
clientMsg.Name = "clientMsg";//设置线程名字
clientMsg.Start(acceptSocket);
}
}
catch (Exception)
{
}
}
/// <summary>
/// 服务器端和客户端通讯的后台线程方法
/// </summary>
/// <param name="sockMsg"></param>
public void ClientMsg(object sockMsg)
{
int temp = socketIndex;
socketIndex++;
Socket socketMsg = sockMsg as Socket;//通讯Socket
IPEndPoint iPEndPoint = socketMsg.RemoteEndPoint as IPEndPoint;
string ipStr = iPEndPoint.Address.ToString();
while (true)
{
//准备一个“数据缓存(数组)”
byte[] msg = new byte[1024 * 1024];
//接收客户端发来的数据,返回数据真实长度
int count = socketMsg.Receive(msg);
//byte数组转换为string
string str = Encoding.UTF8.GetString(msg, 0, count);
if (str=="退出")
{
break;
}
string nameStr = string.Empty;
switch (ipStr)
{
case "192.168.1.135" :
nameStr = "陈泉希";
break;
case "192.168.1.148":
nameStr = "崔昊";
break;
default:
break;
}
Console.WriteLine(nameStr + "发过来的数据:"+str);
SenfMsg(socketMsg,str,ipStr);
}
socketMsg.Shutdown(SocketShutdown.Receive);
socketList[temp].Close();
}
private void SenfMsg(Socket client,string str,string ipStr)
{
foreach (var item in socketList)
{
IPEndPoint iPEndPoint_ = item.RemoteEndPoint as IPEndPoint;
string friendIp = iPEndPoint_.Address.ToString();
if (friendIp != ipStr)
{
isFriend = true;
string nameStr = string.Empty;
switch (ipStr)
{
case "192.168.1.135":
nameStr = "陈泉希";
break;
case "192.168.1.148":
nameStr = "崔昊";
break;
default:
break;
}
if (!string.IsNullOrEmpty(str))
{
byte[] byteArray = Encoding.UTF8.GetBytes(nameStr+"_"+str);
item.Send(byteArray);
}
else
{
Console.WriteLine("客户端信息为空");
}
}
}
if (!isFriend)
{
byte[] byteArray = Encoding.UTF8.GetBytes("没有好友在线");
client.Send(byteArray);
Console.WriteLine("只有一个客户端在线");
}

}
static void Main(string[] args)
{
Server server = new Server();

}
}
}

Client端代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;


namespace Client_Tcp
{
class Client
{
private Socket clientSocket;//客户端通讯套接字
private IPEndPoint serverEndPoiint;//连接到的服务器IP和端口
public Client()
{
serverEndPoiint = new IPEndPoint(IPAddress.Parse("127.0.0.1"),9999);
clientSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
try
{
clientSocket.Connect(serverEndPoiint);
Thread thread = new Thread(ReceiveMsg);
thread.IsBackground = true;
thread.Name = "thread";
thread.Start();
}
catch (Exception)
{
}
Console.WriteLine("已连接服务器");
}
public void SendMsg()
{
while (true)
{
//输入数据
string str = Console.ReadLine();
//转换为字节
byte[] byteArray = Encoding.UTF8.GetBytes(str);
//发送数据
clientSocket.Send(byteArray);
if (str=="退出")
{
break;
}
Console.WriteLine("我:"+ str);
}
//关闭连接
clientSocket.Shutdown(SocketShutdown.Both);
//清理连接资源
clientSocket.Close();
}
/// <summary>
/// 接受服务器信息
/// </summary>
private void ReceiveMsg()
{
while (clientSocket.IsBound)
{
byte[] byteArray = new byte[1024*1024];
int count= clientSocket.Receive(byteArray);
string str = Encoding.UTF8.GetString(byteArray,0,count);
//发送信息的好友名字
string frienfName = str.Split('_')[0];
//发送的具体信息
string msg= str.Split('_')[1];
Console.WriteLine("好友"+ frienfName+":"+ msg);
}
}
static void Main(string[] args)
{
Client client = new Client();
client.SendMsg();
}
}
}

猜你喜欢

转载自www.cnblogs.com/Damon-3707/p/11960083.html