19,502
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Collections;
using System.Net;
using System.Windows.Forms;
using System.Threading;
using System.Data;
namespace SocketServer
{
public class SocketServer
{
private IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse("192.168.0.159"), 6000); //本机地址
public Hashtable htClients = new Hashtable(); //存放客户端的列表
/// <summary>
/// 程序启动时就启动该线程侦听客户端的连接请求
/// </summary>
public void StartListening()
{
const int nPortListen = 6000;
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(ipEndPoint);
listener.Listen(1000);
listener.BeginAccept(new AsyncCallback(OnConnectRequest), listener);
}
/// <summary>
/// 客户端连接时触发连接事件
/// </summary>
/// <param name="ar"></param>
public void OnConnectRequest(IAsyncResult ar)
{
Socket listener = (Socket)ar.AsyncState;
Socket client = listener.EndAccept(ar);
Baohe bh = new Baohe(client);
htClients.Add(client.RemoteEndPoint, bh);
OnConnect(client);
//MessageBox.Show("Client:"+client.RemoteEndPoint.ToString());
listener.BeginAccept(new AsyncCallback(OnConnectRequest), listener);
}
/// <summary>
/// 连接后启动异步接收
/// </summary>
/// <param name="sock"></param>
public void OnConnect(Socket sock)
{
// Check if we were sucessfull
try
{
//sock.EndConnect( ar );
if (sock.Connected)
{
AsyncCallback recieveData = new AsyncCallback(OnRecievedData);
byte[] buff = ((Baohe)htClients[sock.RemoteEndPoint]).buffer;//获取此宝盒对象的buff地址
sock.BeginReceive(buff, 0, buff.Length, SocketFlags.None, recieveData, sock);
}
else
MessageBox.Show("Unable to connect to remote machine", "Connect Failed!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Unusual error during Connect!");
}
}
/// <summary>
/// 异步接收信息时触发事件
/// </summary>
/// <param name="ar"></param>
public void OnRecievedData(IAsyncResult ar)
{
Socket sock = (Socket)ar.AsyncState;
// Check if we got any data
try
{
int nBytesRec = sock.EndReceive(ar);
if (nBytesRec > 0)
{
byte[] buff = ((Baohe)htClients[sock.RemoteEndPoint]).buffer;//获取此客户端对象的buff地址
// Wrote the data to the List
string sRecieved = Encoding.UTF8.GetString(buff, 0, nBytesRec);
ParseMessage(sock, sRecieved);//根据消息做回复
// If the connection is still usable restablish the callback
SetupRecieveCallback(sock);
}
else
{
// If no data was recieved then the connection is probably dead
MessageBox.Show("disconnect from server " + sock.RemoteEndPoint);
sock.Shutdown(SocketShutdown.Both);
sock.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Unusual error druing Recieve!");
}
}
/// <summary>
/// 异步接收继续开启
/// </summary>
/// <param name="sock"></param>
public void SetupRecieveCallback(Socket sock)
{
byte[] buff = ((Baohe)htClients[sock.RemoteEndPoint]).buffer;//获取此客户端对象的buff地址
AsyncCallback recieveData = new AsyncCallback(OnRecievedData);//收到数据时回调数据处理函数
sock.BeginReceive(buff, 0, buff.Length, SocketFlags.None, recieveData, sock);
}
/// <summary>
/// 回复客户端
/// </summary>
/// <param name="sock"></param>
/// <param name="sRecieved"></param>
public void ParseMessage(Socket sock, string sRecieved)
{
//根据sRecieved设置bytedata回复内容
}
/// <summary>
/// 发送客户端消息(参数:发送内容、发送目标)
/// </summary>
public bool sendClient(string sendContext,string sendTarget)
{
Socket clientSocket = ((Baohe)htClients[sendTarget]).socket;//根据键找出一个客户端的socket连接
try
{
byte[] buffer = Encoding.UTF8.GetBytes(sendContext);
AsyncCallback sendcallback = new AsyncCallback(OnSendCallBack);
clientSocket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, sendcallback, clientSocket); //发送命令
}
catch
{
return false;
}
return true;
}
public void OnSendCallBack(IAsyncResult ar)
{
Socket sock = (Socket)ar.AsyncState;
sock.EndSend(ar);
}
}
}