c# Socket网络通讯简单案例
- 客户端类
///引用
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
///参数(ip,端口,电文头,电文体,是否返回)
///该案例为项目案例 电文头29个长度,电文体不统一
public string StartClient(string ip, int Port, string head, string sendInfo, bool returnFlag)
{
string recInfo = "";
try
{
IPAddress Ip = IPAddress.Parse(ip);
IPEndPoint ipPort = new IPEndPoint(Ip, Port);//把ip和端口转化为IPEndPoint实例
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket
clientSocket.Connect(ipPort);//连接到服务器
lock (this){
byte[] bInfo = Encoding.Default.GetBytes(sendInfo);
int sendLen = bInfo.Length;
byte[] bt = new byte[sendLen + 29];
byte[] bLen = Encoding.Default.GetBytes(sendInfo);
byte[] bHead = Encoding.Default.GetBytes(head);
Array.Copy(bHead, 0, bt, 0, bHead.Length);
Array.Copy(bInfo, 0, bt, 29, bInfo.Length);
clientSocket.Send(bt, bt.Length, 0); //发送到服务端
if (returnFlag){
byte[] recLenByte = new byte[5];
clientSocket.Receive(recLenByte, recLenByte.Length, 0);
int recLen = Convert.ToInt16(Encoding.Default.GetString(recLenByte, 0, 5));
byte[] recInfoByte = new byte[recLen];
clientSocket.Receive(recInfoByte, recInfoByte.Length, 0);
recInfo = Encoding.Default.GetString(recInfoByte, 0, recLen).ToString();
}
clientSocket.Close();
return recInfo;
}
}
catch (ArgumentNullException e){ return e.ToString();}
catch (SocketException e){return e.ToString();}
}
- 服务端类
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
public class SocketServer
{
public static int port;///定义端口号
private static System.Threading.Thread TCComunication;//定义线程
public static Socket serverSocket;//定义socket
/// <summary>
///是否断开连接
/// </summary>
public static bool flag;
///赋值 客户端 端口号
public static void SocketServers(int Port)
{
flag = true;
port = Port;
}
///停止监听
public static void exit()
{
flag = false;
System.Threading.Thread.Sleep(1000);
TCComunication.Abort();
serverSocket.Close();
}
///开启监听
public static void Startthread()
{
TCComunication = new Thread(new ThreadStart(Start));
TCComunication.Start();
}
public static void Start()
{
try
{
string recInfo = "";
string host = "192.168.1.1";//配置客户端ip地址
IPAddress ip = IPAddress.Parse(host);
IPEndPoint ipe = new IPEndPoint(ip, port);
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket类
serverSocket.Bind(ipe);//绑定端口
serverSocket.Listen(0);//开始监听
while (flag)
{
Socket temp = serverSocket.Accept();//为新建连接创建新的Socket。
byte[] recLenByte = new byte[1000];//定义一个1000长度的byte数组来接收
temp.Receive(recLenByte, recLenByte.Length, 0);
string str = Encoding.Default.GetString(recLenByte);//转string类型
string head = str.Substring(0,29);//截取电文头部
recInfo = str.Remove(0,29);//删掉电文头 就是电文体
string sendInfo = parseHead(head, recInfo);//根据电文头和电文体 做出对应的操作
if (sendInfo != "")//sendInfo 返回给客户端的信息
{
byte[] bInfo = Encoding.Default.GetBytes(sendInfo);
int sendLen = bInfo.Length;
byte[] bLen = Encoding.Default.GetBytes(sendLen.ToString());
byte[] bt = new byte[sendLen + 5];
Array.Copy(bLen, 0, bt, 0, bLen.Length);
Array.Copy(bInfo, 0, bt, 5, sendLen);
temp.Send(bt, bt.Length, 0);//发送给客户端
}
temp.Close();
if (!flag)
{
temp.Close();
serverSocket.Close();
break;
}
Thread.Sleep(1000);
}
}
catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException: {0}", e);
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
}
public static string parseHead(string head, string info)
{
string heads = head.Substring(head.Length - 25, 6);//截取出对应接口编号
string reNull = "";//回复信息
switch (heads)
{
case "E12345":
reNull = "123";
break;
case "Q12345":
reNull = "456";
break;
case "w12346":
reNull = "789";
break;
default:
break;
}
return reNull;
}
public SocketServer()
{
}
}
}
3.操作实现
- 调用服务端启动监听
//SocketServer:服务端类名
SocketServer.SocketServers(9999);
SocketServer.Startthread();//开始监听
- 调用客户端 向服务端发送电文
SocketClient PCXF = new SocketClient();//初始化创建客户端
string plan_no = PCXF.StartClient(HostIP, port, hread, param, false);//调用客户端向服务端发送数据 plan_no是服务端返回的数据