整体结构
关于怎么具体一步步使用socket我就不说了,有兴趣同学可以看看你得学会并且学得会的Socket编程基础知识,看看我们服务器的结构,我写了一个TcpHelper类来处理服务器操作
首先定义 一个ClientInfo类存放Client信息
/// <summary>
/// 启动服务器,监听客户端请求
/// </summary>
/// <param name="port">服务器端进程口号</param>
public void Run(int port);
/// <summary>
/// 在独立线程中不停地向所有客户端广播消息
/// </summary>
private void Broadcast();
/// <summary>
/// 把客户端消息打包处理(拼接上谁什么时候发的什么消息)
/// </summary>
/// <returns>The message.</returns>
/// <param name="sm">Sm.</param>
private byte[] PackageMessage(SocketMessage sm);
/// <summary>
/// 处理客户端连接请求,成功后把客户端加入到clientPool
/// </summary>
/// <param name="result">Result.</param>
private void Accept(IAsyncResult result);
/// <summary>
/// 处理客户端发送的消息,接收成功后加入到msgPool,等待广播
/// </summary>
/// <param name="result">Result.</param>
private void Recieve(IAsyncResult result);
逐个分析一下把
void run(int port)
这是该类唯一提供的共有方法,供外界调用,来根据port参数创建一个socket
public class ClientInfo
{
public byte[] buffer;
public string NickName { get; set; }
public EndPoint Id { get; set; }
public IntPtr handle { get; set; }
public string Name
{
get
{
if (!string.IsNullOrEmpty(NickName))
{
return NickName;
}
else
{
return string.Format("{0}#{1}", Id, handle);
}
}
}
}
然后是一个SocketMessage类,记录客户端发来的消息
public class SocketMessage
{
public bool isLogin { get; set; }
public ClientInfo Client { get; set; }
public string Message { get; set; }
public DateTime Time { get; set; }
}
然后定义两个全局变量记录所有客户端及所有客户端发来的消息
private Dictionary<Socket, ClientInfo> clientPool = new Dictionary<Socket, ClientInfo>();
private List<SocketMessage> msgPool = new List<SocketMessage>();
然后就是几个主要方法的定义
/// <summary>
/// 启动服务器,监听客户端请求
/// </summary>
/// <param name="port">服务器端进程口号</param>
public void Run(int port);
/// <summary>
/// 在独立线程中不停地向所有客户端广播消息
/// </summary>
private void Broadcast();
/// <summary>
/// 把客户端消息打包处理(拼接上谁什么时候发的什么消息)
/// </summary>
/// <returns>The message.</returns>
/// <param name="sm">Sm.</param>
private byte[] PackageMessage(SocketMessage sm);
/// <summary>
/// 处理客户端连接请求,成功后把客户端加入到clientPool
/// </summary>
/// <param name="result">Result.</param>
private void Accept(IAsyncResult result);
/// <summary>
/// 处理客户端发送的消息,接收成功后加入到msgPool,等待广播
/// </summary>
/// <param name="result">Result.</param>
private void Recieve(IAsyncResult result);
逐个分析一下把
void run(int port)
这是该类唯一提供的共有方法,供外界调用,来根据port参数创建一个socket
public void Run(int port)
{
Thread serverSocketThraed = new Thread(() =>
{
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
server.Bind(new IPEndPoint(IPAddress.Any, port));
server.Listen(10);
server.BeginAccept(new AsyncCallback(Accept), server);
});
serverSocketThraed.Start();
Console.WriteLine("Server is ready");
Broadcast();
}
代码很简单,需要注意的有几点
1.在一个新线程中创建服务器socket,最多允许10个客户端连接。
2.在方法最后调用Broadcast()方法用于向所有客户端广播消息
3.BeginAccept方法,MSDN上有权威解释,但是觉得不够接地气,简单说一下我的理解,首先这个方法是异步的,用于服务器接受一个客户端的连接,第一个参数实际上是回调函数,在C#中使用委托,在回调函数中通过调用EndAccept就可以获得尝试连接的客户端socket,第二个参数是包含请求state的对象,传入server socket对象本身就可以了
void Accept(IAsyncResult result)
方法用于处理客户端连接请求
private void Accept(IAsyncResult result)
{
Socket server = result.AsyncState as Socket;
Socket client = server.EndAccept(result);
try
{
//处理下一个客户端连接
server.BeginAccept(new AsyncCallback(Accept), server);
byte[] buffer = new byte[1024];
//接收客户端消息
client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(Recieve), client);
ClientInfo info = new ClientInfo();
info.Id = client.RemoteEndPoint;
info.handle = client.Handle;
info.buffer = buffer;
//把客户端存入clientPool
this.clientPool.Add(client, info);
Console.WriteLine(string.Format("Client {0} connected", client.RemoteEndPoint));
}
catch (Exception ex)
{
Console.WriteLine("Error :\r\n\t" + ex.ToString());
}
}
BeginRecieve方法的MSDN有解释,和Accept一样也是异步处理,接收客户端消息,放入第一个参数中,它也传入了一个回调函数的委托,和带有socket state的对象,用于处理下一次接收。我们把接收成功地客户端socket及其对应信息存放到clientPool中
void Recieve(IAsyncResult result)
方法用于接收客户端消息,并把所有消息及其发送者信息存入msgInfo,等待广播
private void Recieve(IAsyncResult result)
{
Socket client = result.AsyncState as Socket;
if (client == null || !clientPool.ContainsKey(client))
{
return;
}
try
{
int length = client.EndReceive(result);
byte[] buffer = clientPool[client].buffer;
//接收消息
client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(Recieve), client);
string msg = Encoding.UTF8.GetString(buffer, 0, length);
SocketMessage sm = new SocketMessage();
sm.Client = clientPool[client];
sm.Time = DateTime.Now;
Regex reg = new Regex(@"{<(.*?)>}");
Match m = reg.Match(msg);
if (m.Value != "") //处理客户端传来的用户名
{
clientPool[client].NickName = Regex.Replace(m.Value, @"{<(.*?)>}", "$1");
sm.isLogin = true;
sm.Message = "login!";
Console.WriteLine("{0} login @ {1}", client.RemoteEndPoint,DateTime.Now);
}
else //处理客户端传来的普通消息
{
sm.isLogin = false;
sm.Message = msg;
Console.WriteLine("{0} @ {1}\r\n {2}", client.RemoteEndPoint,DateTime.Now,msg);
}
msgPool.Add(sm);
}
catch
{
//把客户端标记为关闭,并在clientPool中清除
client.Disconnect(true);
Console.WriteLine("Client {0} disconnet", clientPool[client].Name);
clientPool.Remove(client);
}
}
这个的代码都很简单,就不多解释了,我加入了用户名处理用于广播客户端消息的时候显示客户端自定义的昵称而不是生硬的ip地址+端口号,当然这里需要客户端配合
Broadcast()
服务器已经和客户端连接成功,并且接收到了客户端消息,我们就可以看看该怎么广播消息了,Broadcast()方法已经在run()方法内调用,看看它是怎么运作广播客户端消息的
private void Broadcast()
{
Thread broadcast = new Thread(() =>
{
while (true)
{
if (msgPool.Count > 0)
{
byte[] msg = PackageMessage(msgPool[0]);
foreach (KeyValuePair<Socket, ClientInfo> cs in clientPool)
{
Socket client = cs.Key;
if (client.Connected)
{
client.Send(msg, msg.Length, SocketFlags.None);
}
}
msgPool.RemoveAt(0);
}
}
});
broadcast.Start();
}
Broadcast()方法启用了一个新线程,循环检测msgPool是否为空,当不为空的时候遍历所有客户端,调用send方法发送msgPool里面的第一条消息,然后清除该消息继续检测,直到消息广播完,其实这就是一个阉割版的观察者模式 ,顺便看一下打包数据方法
private byte[] PackageMessage(SocketMessage sm)
{
StringBuilder packagedMsg = new StringBuilder();
<span style="white-space:pre"> </span> if(sm!=null)
<span style="white-space:pre"> </span> {
if (!sm.isLogin) //消息是login信息
{
packagedMsg.AppendFormat("{0} @ {1}:\r\n ", sm.Client.Name, sm.Time.ToShortTimeString());
packagedMsg.Append(sm.Message);
}
else //处理普通消息
{
packagedMsg.AppendFormat("{0} login @ {1}", sm.Client.Name, sm.Time.ToShortTimeString());
}
<span style="white-space:pre"> </span> <pre name="code" class="csharp"> }
return Encoding.UTF8.GetBytes(packagedMsg.ToString()); }
如何使用
static void Main(string[] args)
{
TcpHelper helper = new TcpHelper();
helper.Run(8080);
}
这样我们就启用了server,看看简单的客户端实现,原理类似,不再分析了
class Program
{
private static byte[] buf = new byte[1024];
static void Main(string[] args)
{
Console.Write("Enter your name: ");
string name = Console.ReadLine();
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
client.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080));
Console.WriteLine("Connected to server, enter $q to quit");
name = "{<" + name.Trim() + ">}";
byte[] nameBuf = Encoding.UTF8.GetBytes(name);
client.BeginSend(nameBuf, 0, nameBuf.Length, SocketFlags.None, null, null);
client.BeginReceive(buf, 0, buf.Length, SocketFlags.None, new AsyncCallback(Recieve), client);
while (true)
{
string msg = Console.ReadLine();
if (msg == "$q")
{
client.Close();
break;
}
byte[] output = Encoding.UTF8.GetBytes(msg);
client.BeginSend(output, 0, output.Length, SocketFlags.None, null, null);
}
Console.Write("Disconnected. Press any key to exit... ");
Console.ReadKey();
}
private static void Recieve(IAsyncResult result)
{
try
{
Socket client = result.AsyncState as Socket;
int length = client.EndReceive(result);
string msg = Encoding.UTF8.GetString(buf, 0, length);
Console.WriteLine(msg);
client.BeginReceive(buf, 0, buf.Length, SocketFlags.None, new AsyncCallback(Recieve), client);
}
catch
{
}
}
}
源码下载地址:http://download.csdn.net/detail/flyaurora/9396878
内容转载自:http://www.cnblogs.com/dolphinX/p/3462496.html