Socket一般用于网络之间的通信,在这里,实现的是服务端与客户端的简单消息通信。
首先是客户端的搭建,一般步骤是先建立Socket绑定本地的IP和端口,并对远端连接进行连接进行监听,这里的监听一般开启后台线程进行循环处理;如果远端有连接到本机的Socket的端口,则获取一个新的Socket对象并重新添加一个线程用于对远端地址进行消息通信(消息的收发),这样,服务端的Socket就简单实现,下面是winForm的具体实现。
一、先建立Socket的服务类SocketServerManager,用于对Socket各种操作的统一管理:
public class SocketManager
{
Socket _socket = null;
EndPoint _endPoint = null;
bool _isListening = false;
int BACKLOG = 10;
public SocketManager(string ip, int port)
{
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress _ip = IPAddress.Parse(ip);
_endPoint = new IPEndPoint(_ip, port);
}
public void Start()
{
_socket.Bind(_endPoint); //绑定端口
_socket.Listen(BACKLOG); //开启监听
Thread acceptServer = new Thread(AcceptWork); //开启新线程处理监听
acceptServer.IsBackground = true;
_isListening = true;
acceptServer.Start();
}
public void AcceptWork()
{
while (_isListening)
{
Socket acceptSocket = _socket.Accept();
if (acceptSocket != null)
{
Thread socketConnectedThread = new Thread(newSocketReceive);
socketConnectedThread.IsBackground = true;
socketConnectedThread.Start(acceptSocket);
}
Thread.Sleep(200);
}
}
public void newSocketReceive(object obj)
{
Socket socket = obj as Socket;
while (true)
{
try
{
if (socket == null) return;
//这里向系统投递一个接收信息的请求,并为其指定ReceiveCallBack做为回调函数
socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, ReceiveCallBack, buffer);
}
catch (Exception ex)
{
return;
}
Thread.Sleep(100);
}
}
private void ReceiveCallBack(IAsyncResult ar)
{
}
}
public class SockeServertManager
上面是Socket管理类的模型,具体的方法是初始化和开启监听,接下来就是在Form的界面调用建立类和Start方法。
客户端同样是初始化socket,然后就不是监听socket,而是调用Connect连接指定的Socket地址,最后是开启新的线程接收和发送消息。
public class SocketClientManager
{
public Socket _socket = null;
public EndPoint endPoint = null;
public bool _isConnected = false;