C#进程间通信的⼏种⽅式:Socket通信⽅式⼆:Socket通信
套接字(Socket)是⽀持TCP/IP协议(安全)和UDP协议(快速)的⽹络通信的基本操作单元。套接字包含进⾏⽹络通信必须的五种信息:连接使⽤的协议,本地主机的IP地址,本地进程的协议端⼝,远地主机的IP地址,远地进程的协议端⼝。为了满⾜不同程序对通信质量和性能的要求,⼀般的⽹络系统都提供了流式、数据报式、原始3种不同类型的套接字。
Socket通信⽅式:
同步:客户端在发送请求之后必须等到服务器回应之后才可以发送下⼀条请求——串⾏运⾏。
异步:客户端请求之后,不必等到服务器回应之后就可以发送下⼀条请求——并⾏运⾏。
在C/S编程模式下Socket通信的过程:
服务器端:打开通信通道(告诉本地机器,愿意在该通道上接受客户请求)——监听(等待客户请求)——接受请求(创建专⽤链接进⾏读写)——处理完毕(关闭通信通道)。
客户端:打开通信通道(连接服务器)——数据交互——关闭信道。
下⾯以流式,TCP协议,异步通信,服务器端和客户端⼀对多(同时适⽤⼀对⼀)为例写出控制台应⽤程序:
1、SocketHelper类:
using System;
using System.Net;
using System.Net.Sockets;
namespace SocketHelper
{
public class ClientSession
{
public Socket ClientSocket { get; set; }
public string IP;
public ClientSession(Socket clientSocket)
{
this.ClientSocket = clientSocket;
this.IP = GetIPStr();
}
public string GetIPStr()
{
string resStr = ((IPEndPoint)ClientSocket.RemoteEndPoint).Address.ToString();
return resStr;
}
}
public class SocketConnection:IDisposable
{
public Byte[] msgBuffer = new byte[1024];
private Socket _clientSocket = null;
public Socket ClientSocket
{
get { return this._clientSocket; }
}
#region 构造
public SocketConnection(Socket sock)
{
this._clientSocket = sock;
}
#endregion
#region 连接
public void Connect(IPAddress ip,int port)
{
this.ClientSocket.BeginConnect(ip, port, ConnectCallback, this.ClientSocket);
}
}
private void ConnectCallback(IAsyncResult ar)
{
try
{
Socket handler = (Socket)ar.AsyncState;
handler.EndConnect(ar);
}
catch (SocketException ex)
{
}
}
#endregion
#region 发送数据
public void Send(string data)
{
Send(System.Text.Encoding.UTF8.GetBytes(data));
}
private void Send(byte[] byteData)
{
try
{
this.ClientSocket.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), this.ClientSocket);            }
catch (SocketException ex)
{
}
}
private void SendCallback(IAsyncResult ar)
{
try
{
Socket handler = (Socket)ar.AsyncState;
handler.EndSend(ar);
}
catch (SocketException ex)
{
}
}
#endregion
#region 接收数据
public void ReceiveData()
{
ClientSocket.BeginReceive(msgBuffer, 0, msgBuffer.Length, 0, new AsyncCallback(ReceiveCallback), null);
}
private void ReceiveCallback(IAsyncResult ar)
{
try
{
int REnd = ClientSocket.EndReceive(ar);
if(REnd >0)
{
byte[] data = new byte[REnd];
Array.Copy(msgBuffer, 0, data, 0, REnd);
//在此处对数据进⾏处理
ClientSocket.BeginReceive(msgBuffer, 0, msgBuffer.Length, 0, new AsyncCallback(ReceiveCallback), null);
}
else
{
Dispose();
}
}
}
catch (SocketException ex)
{
}
}
public void Dispose()
{
try
{
ClientSocket.Shutdown(SocketShutdown.Both);                ClientSocket.Close();
}
catch (Exception ex)
{
}
}
#endregion
}
}
2、服务器端程序:
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace SocketServer
{
class Program
{
static void Main(string[] args)
{
int port = 6000;
int MaxConnection = 10;
Hashtable clientSessionTable = new Hashtable();
object clientSessionLock = new object();
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, port);
Socket socketLister = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socketLister.Bind(localEndPoint);
try
{
socketLister.Listen(MaxConnection);
Console.WriteLine("服务器Socket监听已经打开...");
while (true)
{
Socket clientSocket = socketLister.Accept();
SocketHelper.ClientSession clientSession = new SocketHelper.ClientSession(clientSocket);
进程通信方式lock(clientSessionLock)
{
if (!clientSessionTable.ContainsKey(clientSession.IP))
{
clientSessionTable.Add(clientSession.IP, clientSession);
}
}
Console.WriteLine("建⽴连接:{0}",clientSession.IP);
SocketHelper.SocketConnection socketConnection = new SocketHelper.SocketConnection(clientSocket);                    socketConnection.ReceiveData();
Thread.Sleep(1000);
string recStr = "";
recStr += Encoding.ASCII.GetString(socketConnection.msgBuffer);
Console.WriteLine("服务器获得信息:{0}", recStr);
}
}
catch (SocketException ex)
{
}
}
}
}
3、客户端程序:

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。