通信Socket
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;//socket的空间
using System.Net;//IP和端口引用的空间
using System.Threading;
namespace TCP服务器端 //先发再收
{
class Program
{
static Queue<string> Quexiaoxi = new Queue<string>();
static Dictionary<Socket, string> clientSocketDic = new Dictionary<Socket, string>();
static void Main(string[] args)
{
StartServerSync();
}
static void StartServerSync()
{
//先创建一个服务器端Socket
Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// 127.0.0.1Any(万能本机IP)
IPAddress iPAddress = IPAddress.Parse("192.168.53.28");
IPEndPoint iPEndPoint = new IPEndPoint(iPAddress, 88);//80端口是内置http的(特殊端口)
//绑定IP端口
serverSocket.Bind(iPEndPoint);
//处理链接队列客户端的个数 0代表不限制
serverSocket.Listen(0);
Console.WriteLine("服务器成功开启");
//开启线程管理客户链接
Thread childThread = new Thread(myAcceptThread);
childThread.Start(serverSocket);
childThread.IsBackground = true;
//开启管理群发线程
Thread processThread = new Thread(myProcessThread);
processThread.Start();
processThread.IsBackground = true;
}//同步
static void myProcessThread()
{
while (true)
{
if (Quexiaoxi.Count > 0)
{
string readString = Quexiaoxi.Dequeue();
Console.WriteLine("正在群发:{0}", readString);
byte[] snedBytes = Encoding.UTF8.GetBytes(readString);
foreach (Socket client in clientSocketDic.Keys)
{
client.Send(snedBytes);
}
}
Thread.Sleep(200);
}
}
static void myAcceptThread(object socket)
{
Socket serverSocket = socket as Socket;
while (true)
{
try
{
Socket clientSocket = serverSocket.Accept();
string msg = "欢迎" + clientSocket.RemoteEndPoint.ToString();
Console.WriteLine(msg);
Quexiaoxi.Enqueue(msg);
clientSocketDic.Add(clientSocket, clientSocket.RemoteEndPoint.ToString());
Thread clientThread = new Thread(myClientThread);
clientThread.Start(clientSocket);
clientThread.IsBackground = true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
serverSocket.Close();
break;
}
}
}
static void myClientThread(object socket)
{
Socket clientSocket = socket as Socket;
try
{
int count = 0;
while (true)
{
byte[] dataBuffer = new byte[1024];//缓存的字节数组 要足够大
count = clientSocket.Receive(dataBuffer);
if (count == 0)
{
string tip = string.Format("客户端{0}断开连接", clientSocketDic[clientSocket]);
Console.WriteLine(tip);
Quexiaoxi.Enqueue(tip);
clientSocket.Close();
break;
}
else
{
string msg = Encoding.UTF8.GetString(dataBuffer, 0, count);//接受消息
Console.WriteLine("接收到客户端{0}:{1}", clientSocket.RemoteEndPoint.ToString(), msg);//打印
Quexiaoxi.Enqueue(clientSocketDic[clientSocket] + msg);//存入队列
}
}
}
catch (Exception e)
{
string tip = string.Format("{0}因为异常({1})退出", clientSocketDic[clientSocket], e.Message);
Console.WriteLine(tip);
clientSocketDic.Remove(clientSocket);//从字典中移除
Quexiaoxi.Enqueue(tip);//加入队列(最后一句话)
clientSocket.Close();
}
}