using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Web.Script.Serialization;
namespace SocketServer
{
public class SocketHost
{
private IDictionary<Socket, byte[]> socketClientSesson = new Dictionary<Socket, byte[]>();
private List<string> message = new List<string>();
private Boolean isClear = true;
public int Port { get; set; }
public void Start()
{
Boardcast();
var socketThread = new Thread(() =>
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, this.Port);
//绑定到通道上
socket.Bind(iep);
//侦听
socket.Listen(6);
//通过异步来处理
socket.BeginAccept(new AsyncCallback(Accept), socket);
});
socketThread.Start();
Console.WriteLine("Server Started");
}
private void Accept(IAsyncResult ia)
{
Socket socket = ia.AsyncState as Socket;
var client = socket.EndAccept(ia);
socket.BeginAccept(new AsyncCallback(Accept), socket);
byte[] buf = new byte[1024];
this.socketClientSesson.Add(client, buf);
try
{
client.BeginReceive(buf, 0, buf.Length, SocketFlags.None, new AsyncCallback(Receive), client);
string sessionId = client.RemoteEndPoint.ToString() + " - " + client.Handle.ToString();
Console.WriteLine("Client ({0}) Connected", sessionId);
}
catch (Exception ex)
{
Console.WriteLine("Error:\r\n" + ex.ToString());
}
}
private void Receive(IAsyncResult ia)
{
var client = ia.AsyncState as Socket;
if (client == null || !this.socketClientSesson.ContainsKey(client))
{
return;
}
int count = client.EndReceive(ia);
byte[] buf = this.socketClientSesson[client];
if (count > 0)
{
try
{
client.BeginReceive(buf, 0, buf.Length, SocketFlags.None, new AsyncCallback(Receive), client);
string context = Encoding.UTF8.GetString(buf, 0, count);
PushMessage(context);
}
catch (Exception ex)
{
Console.WriteLine("Receive Error :\r\n{0}", ex.ToString());
}
}
else
{
try
{
string sessionId = client.RemoteEndPoint.ToString() + " - " + client.Handle.ToString();
client.Disconnect(true);
this.socketClientSesson.Remove(client);
Console.WriteLine("Client ({0}) Disconnet", sessionId);
}
catch (Exception ex)
{
Console.WriteLine("Error: \r\n" + ex.ToString());
}
}
}
private void PushMessage(string context)
{
while (context.EndsWith("\n") || context.EndsWith("\0"))
{
context = context.Remove(context.Length - 1);
}
Console.WriteLine("Get : {0}", context);
message.Add(context);
isClear = false;
}
private void Boardcast()
{
var boardcaseThread = new Thread(() =>
{
while (true)
{
if (!isClear)
{
byte[] tmp = Encoding.UTF8.GetBytes(message[0] + "\0\n");
foreach (KeyValuePair<Socket, byte[]> node in this.socketClientSesson)
{
Socket client = node.Key;
client.Send(tmp, tmp.Length, SocketFlags.None);
}
message.RemoveAt(0);
isClear = message.Count > 0 ? false : true;
}
}
});
boardcaseThread.Start();
}
}
}
用C#编写可以广播的SOCKET服务器端
最新推荐文章于 2023-03-27 22:55:12 发布