Socket实现简单的指定客户端发送信息(效果如下图)
不多说了,直接上代码:
server端:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Net;
class server
{
//创建一个和客户端通信的套接字
static Socket SocketWatch = null;
//定义一个集合,存储客户端信息
static Dictionary<string, Socket> ClientConnectionItems = new Dictionary<string, Socket> { };
public static string cID;
static void Main(string[] args)
{
//端口号(用来监听的)
int port = 6000;
IPAddress ip = IPAddress.Any;
//将IP地址和端口号绑定到网络节点point上
IPEndPoint ipe = new IPEndPoint(ip, port);
//定义一个套接字用于监听客户端发来的消息,包含三个参数(IP4寻址协议,流式连接,Tcp协议)
SocketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//监听绑定的网络节点
SocketWatch.Bind(ipe);
//将套接字的监听队列长度限制为20
SocketWatch.Listen(20);
//负责监听客户端的线程:创建一个监听线程
Thread threadwatch = new Thread(WatchConnecting);
//将窗体线程设置为与后台同步,随着主线程结束而结束
threadwatch.IsBackground = true;
//启动线程
threadwatch.Start();
Console.WriteLine("开启监听......");
Console.WriteLine("点击输入任意数据回车退出程序......");
Console.ReadKey();
SocketWatch.Close();
}
//监听客户端发来的请求
static void WatchConnecting()
{
Socket connection = null;
//持续不断监听客户端发来的请求
while (true)
{
// string cID;
try
{
connection = SocketWatch.Accept();
}
catch (Exception ex)
{
//提示套接字监听异常
Console.WriteLine(ex.Message);
break;
}
byte[] idrec = new byte[1024 * 1024];
int length = connection.Receive(idrec);
cID = Encoding.UTF8.GetString(idrec, 0, length);
ClientConnectionItems.Add(cID, connection);
//显示与客户端连接情况
Console.WriteLine("\r\n[客户端\"" + cID + "\"建立连接成功! 客户端数量:" + ClientConnectionItems.Count + "]");
//获取客户端的IP和端口号
IPAddress clientIP = (connection.RemoteEndPoint as IPEndPoint).Address;
int clientPort = (connection.RemoteEndPoint as IPEndPoint).Port;
string sendmsg = "[" + "本端:" + cID + " 连接服务端成功!]";
byte[] arrSendMsg = Encoding.UTF8.GetBytes(sendmsg);
connection.Send(arrSendMsg);
//创建一个通信线程
Thread thread = new Thread(recv);
//设置为后台线程,随着主线程退出而退出
thread.IsBackground = true;
//启动线程
thread.Start(connection);
}
}
static void recv(object socketclientpara)
{
Socket socketServer = socketclientpara as Socket;
while (true)
{
try
{
byte[] arrServerRecMsg = new byte[1024 * 1024];
int length = socketServer.Receive(arrServerRecMsg);
//将机器接受到的字节数组转换为人可以读懂的字符串
string strSRecMsg = Encoding.UTF8.GetString(arrServerRecMsg, 0, length);
string ccID = strSRecMsg.Substring(0, 4);
int len = strSRecMsg.Length;
string hc=cID+":"+strSRecMsg.Substring(4,len-4);
Console.WriteLine( DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff") + "]\r\n" + strSRecMsg);
//判断是否包含这个客户端
bool contains = ClientConnectionItems.ContainsKey(ccID);
if (contains)
{
ClientConnectionItems[ccID].Send(Encoding.UTF8.GetBytes( hc));
}
else
{
Console.WriteLine("输入有误,不予转发\r\n");
}
arrServerRecMsg.DefaultIfEmpty();
}
catch (Exception)
{
string temp = ClientConnectionItems.First().Key;
//提示套接字监听异常
Console.WriteLine("\r\n[客户端\"" + socketServer.RemoteEndPoint + "\"已经中断连接! 客户端数量:" + ClientConnectionItems.Count + "]");
ClientConnectionItems.Remove(ClientConnectionItems.First().Key);
Console.WriteLine("\r\n[客户端\"" + temp + "\"已经中断连接! 客户端数量:" + ClientConnectionItems.Count + "]");
break;
}
}
}
}
client端(这里只上传了num3端,想创建更多客户端改改名称就行):
using System;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Net;
class client1
{
//创建1个客户端套接字和1个负责监听服务端请求的线程
static Thread ThreadClient = null;
static Socket SocketClient = null;
static void Main(string[] args)
{
try
{
int port = 6000;
string host = "127.0.0.1";//服务器端ip地址
IPAddress ip = IPAddress.Parse(host);
IPEndPoint ipe = new IPEndPoint(ip, port);
//定义一个套接字监听
SocketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
//客户端套接字连接到网络节点上,用的是Connect
SocketClient.Connect(ipe);
//本客户端的ID
string sendsStr = "num3";
ClientSendMsg(sendsStr);
}
catch (Exception)
{
Console.WriteLine("连接失败!\r\n");
Console.ReadLine();
return;
}
ThreadClient = new Thread(Recv);
ThreadClient.IsBackground = true;
ThreadClient.Start();
Thread.Sleep(1000);
Console.WriteLine("请输入内容<按Enter键发送>:\r\n");
while(true)
{
string sendStr = Console.ReadLine();
if (sendStr.Length <= 4)
{
Console.WriteLine("输入信息长度小于5个字符,请重新输入");
}
else if (sendStr.Substring(0,4)=="num3")
{
Console.WriteLine("请不要给自己发送信息");
}
else
{
ClientSendMsg(sendStr);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
//接收服务端发来信息的方法
public static void Recv()
{
//持续监听服务端发来的消息
while (true)
{
try
{
//定义一个1M的内存缓冲区,用于临时性存储接收到的消息
byte[] arrRecvmsg = new byte[1024 * 1024];
//将客户端套接字接收到的数据存入内存缓冲区,并获取长度
int length = SocketClient.Receive(arrRecvmsg);
//将套接字获取到的字符数组转换为人可以看懂的字符串
string strRevMsg = Encoding.UTF8.GetString(arrRecvmsg, 0, length);
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff") + "\r\n" + strRevMsg + "\r\n");
}
catch (Exception ex)
{
Console.WriteLine("远程服务器已经中断连接!" + ex.Message + "\r\n");
break;
}
}
}
//发送字符信息到服务端的方法
public static void ClientSendMsg(string sendMsg)
{
//将输入的内容字符串转换为机器可以识别的字节数组
byte[] arrClientSendMsg = Encoding.UTF8.GetBytes(sendMsg);
//调用客户端套接字发送字节数组
SocketClient.Send(arrClientSendMsg);
}
}