之前写过一次关于Socket通信的连接方式,经过一个月的使用,发现了一些问题,今天重新将Socket通信的客户端连接方式进行整理,希望对有需要的人能有一点点小的帮助。
首先是客户端连接服务的类,代码如下:
public class ClientConsole
{
//使用最新的方式进行连接
public Socket connect()
{
IPAddress ip = IPAddress.Parse("127.0.0.1");
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
clientSocket.Connect(new IPEndPoint(ip, 8005));
}
catch (Exception e)
{
return null;
}
return clientSocket;
}
/// <summary>
/// 开始连接socket,发送消息并接受返回信息
/// </summary>
/// <param name="param"></param>
/// <returns></returns>
public string sendContent(Socket socket, string param)
{
string rtn = null;
try
{
if (socket != null)
{
bool isSend = send(socket, param);
shutdownSend(socket);
//等待接收消息的socket时间设置为10s
socket.ReceiveTimeout = 1000 * 10;
if (isSend)
{
rtn = read(socket, param);
shutdownRead(socket);
}
}
}
catch (Exception e)
{
rtn = e.Message;
}
finally
{
closeConect(socket);
}
return rtn;
}
/// <summary>
/// 开始发送信息
/// </summary>
/// <param name="socket"></param>
/// <param name="content"></param>
/// <returns></returns>
public bool send(Socket socket, string content)
{
bool result = false;
try
{
socket.Send(Encoding.UTF8.GetBytes(content));
result = true;
}
catch (Exception e)
{
result = false;
}
return result;
}
/// <summary>
/// 关闭掉发送的socket
/// </summary>
/// <param name="socket"></param>
public void shutdownSend(Socket socket)
{
socket.Shutdown(SocketShutdown.Send);
}
/// <summary>
/// 关闭掉接收的socket
/// </summary>
/// <param name="socket"></param>
public void shutdownRead(Socket socket)
{
socket.Shutdown(SocketShutdown.Receive);
}
/// <summary>
/// 接收银行的返回数据
/// </summary>
/// <param name="socket"></param>
/// <param name="mess"></param>
/// <returns></returns>
public string read(Socket socket, string mess)
{
string rtn = "";
try
{
//通过clientSocket接收数据
int len = 0;
int size = 0;//定义一个接收所有信息的数组长度
byte[] buf = new byte[1024];
len = socket.Receive(buf, 0, 16, SocketFlags.None);
//使用utf-8进行解码
string param = Encoding.UTF8.GetString(buf, 0, len);
//定义一个接收xml报文长度的参数
int infoLen = int.Parse(param.Substring(param.LastIndexOf(" ")));
size = infoLen + 48;
byte[] bufs = new byte[size];
int receiveNumber = socket.Receive(bufs, 0, bufs.Length, SocketFlags.None);
rtn = Encoding.UTF8.GetString(bufs, 0, receiveNumber);
}
catch (Exception e)
{
rtn = e.Message;
}
return rtn;
}
/// <summary>
/// 关闭所有的流以及socket连接
/// </summary>
/// <param name="clientSocket"></param>
public void closeConect(Socket clientSocket)
{
clientSocket.Close();
}
}
在系统中的具体调用方式,代码如下:
//进行socket连接
string param="要发送的消息内容";
ClientConsole client = new ClientConsole();
Socket socket = client.connect();
mess = client.sendContent(socket, param);
//mess就是服务端返回的消息内容,你可以根据你的业务需要进行相应的处理即可
...