用C#编写可以广播的SOCKET服务器端


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();
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值