socket连接与信息交互
1.客户端采用与服务端的连接,代码如下:
namespace SocketConsoleClient
{
public class ClientConsole
{
private static byte[] result = new byte[1024];
/// <summary>
/// 连接到服务器
/// </summary>
public string AsynConnect(string param)
{
//设定服务器IP地址
IPAddress ip = IPAddress.Parse("127.0.0.1");
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
string result = "";
try
{
clientSocket.Connect(new IPEndPoint(ip, 2000)); //配置服务器IP与端口
//Console.WriteLine("连接服务器成功");
//result += "连接服务器成功" + "\n";
//连接成功了接收服务器返回消息
result += AsynRecive(clientSocket) + "\n";
//给服务器发送消息
//string message = "你好,服务器,你帮我查询一下这个IP在哪啦?";
result += AsynSend(clientSocket, param) + "\n";
result += AsynRecive(clientSocket) + "\n";
//关闭Socket连接
closeConect(clientSocket);
//Console.WriteLine("发送完毕,按回车键退出");
//Console.ReadLine();
}
catch
{
//Console.WriteLine("连接服务器失败,请按回车键退出!");
return "连接服务器失败,请按回车键退出!";
}
return result;
}
/// <summary>
/// 接收消息
/// </summary>
/// <param name="socket"></param>
public string AsynRecive(Socket clientSocket)
{
string resultInfo = "";
try
{
//通过clientSocket接收数据
int receiveLength = clientSocket.Receive(result);
//Console.WriteLine("接收服务器消息:{0}", Encoding.UTF8.GetString(result, 0, receiveLength));
resultInfo += String.Format("ServerMessage:{0}", Encoding.UTF8.GetString(result, 0, receiveLength));
}
catch (Exception ex)
{
}
return resultInfo;
}
/// <summary>
/// 发送消息
/// </summary>
/// <param name="socket"></param>
/// <param name="message"></param>
public string AsynSend(Socket clientSocket, string message)
{
string result = "";
//通过 clientSocket 发送数据
//for (int i = 0; i < 10; i++)
//{
try
{
Thread.Sleep(1000); //等待1秒钟
//string sendMessage = "client send Message Hellp " + DateTime.Now;
clientSocket.Send(Encoding.UTF8.GetBytes(message));
//Console.WriteLine("向服务器发送消息:{0}", sendMessage + message);
//result += String.Format("向服务器发送消息:{0}", message);
}
catch
{
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
result = "信息发送异常,已关闭相关流!";
}
//}
return result;
}
/// <summary>
/// 关闭所有的流以及socket连接
/// </summary>
/// <param name="clientSocket"></param>
public void closeConect(Socket clientSocket)
{
clientSocket.Close();
}
}
}
2.服务器端用于接收消息与返回响应,代码如下:
namespace SPDBANKConsoleApplication
{
class Program
{
//private static byte[] result = new byte[1024];
private static int myProt = 2000; //端口
static Socket serverSocket;
static void Main(string[] args)
{
//服务器IP地址
IPAddress ip = IPAddress.Parse("127.0.0.1");
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(new IPEndPoint(ip, myProt)); //绑定IP地址:端口
serverSocket.Listen(10); //设定最多10个排队连接请求
Console.WriteLine("启动监听{0}成功", serverSocket.LocalEndPoint.ToString());
//通过Clientsoket发送数据
Thread myThread = new Thread(ListenClientConnect);
myThread.Start();
//启动带参数的线程方法
//Thread t2 = new Thread(new ParameterizedThreadStart(TestMethod));
//t2.Start("hahha");
//Console.ReadLine();
}
public static void TestMethod(object data)
{
string datastr = data as string;
Console.WriteLine("带参数的线程函数,参数为:{0}", datastr);
}
/// <summary>
/// 监听客户端连接
/// </summary>
private static void ListenClientConnect()
{
while (true)
{
Socket clientSocket = serverSocket.Accept();
//给客户端回复消息
clientSocket.Send(Encoding.UTF8.GetBytes("Success Connect!"));
//接收客户端的消息
Thread receiveThread = new Thread(ReceiveMessage);
receiveThread.Start(clientSocket);
}
}
/// <summary>
/// 接收消息
/// </summary>
/// <param name="clientSocket"></param>
private static void ReceiveMessage(object clientSocket)
{
Socket myClientSocket = (Socket)clientSocket;
while (true)
{
try
{
//通过clientSocket接收数据
int len = 0;
int size = 0;//定义一个接收所有信息的数组长度
size = myClientSocket.Available;
byte[] bufs = new byte[size];
int bufslen = 0;//需要接收的信息长度,用于数据的读取
int count = 0;
byte[] buf = new byte[5 * 1024];//定义一个5K大小的数组用于接收数据
while (true)
{
int num = myClientSocket.Available;
if (num <= 0)
{
break;
}
else
{
len = myClientSocket.Receive(buf, 5 * 1024, SocketFlags.None);
if (len > 0)
{
for (int i = 0; i < len; i++)
{
bufs[5 * 1024 * count + i] = buf[i];
}
bufslen += len;
count += 1;
}
}
}
//int receiveNumber = myClientSocket.Receive(bigBuffer);
//将客户端传过来的参数写入txt文件
string path = "d:\\xmlTest\\" + DateTime.Now.ToString("yyyyMMddHHmmdd") + ".txt";
FileStream fs = File.Create(path);
StreamWriter sw = new StreamWriter(fs, Encoding.Default);
//sw.WriteLine(Encoding.UTF8.GetString(bigBuffer, 0, receiveNumber));
sw.WriteLine(Encoding.UTF8.GetString(bufs, 0, bufslen));
sw.Flush();
sw.Close();
//会员账号信息请求
//string cliengMessage = Encoding.UTF8.GetString(bigBuffer, 0, receiveNumber);
string cliengMessage = Encoding.UTF8.GetString(bufs, 0, bufslen);
//获取头部信息
string headInfo = cliengMessage.Split('<')[0];
int index = cliengMessage.IndexOf('<');//获取第一个<出现的位置
//获取xml内容部分
string xmlInfo = cliengMessage.Substring(index);
//对xml内容进行解析
XmlDocument xml = new XmlDocument();
xml.LoadXml(xmlInfo);
//解析Header内容
XmlNodeList rootNode = xml.GetElementsByTagName("Header");
string fundId = "";//网站ID
string tradeCode = "";//交易代码
string errorCode = "";//错误代码
string errorMessage = "";//错误描述
foreach (XmlNode xxNode in rootNode)
{
//读取xml的header内容
XmlElement xmlelement = xxNode as XmlElement;
fundId = xmlelement.SelectSingleNode("Fund_Id").InnerText;
tradeCode = xmlelement.SelectSingleNode("Trade_Code").InnerText;
errorCode = xmlelement.SelectSingleNode("Error_Code").InnerText;
errorMessage = xmlelement.SelectSingleNode("Error_Message").InnerText;
}
if (tradeCode.Equals("1004"))
{
//相应会员账号请求
string toClientMessage = "";//给客户端返回信息
string toClientXmlMessage = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Envelope><Header><Fund_Id>" + fundId + "</Fund_Id><Trade_Code>" + tradeCode + "</Trade_Code><Error_Code></Error_Code><Error_Message></Error_Message></Header><Body><record>< Member_Id > 888077 </ Member_Id >< Account_Code > 19878278987623674872 </ Account_Code >< Succeed_Flag > 0000 </ Succeed_Flag ></ record ></Body></Envelope>";
toClientMessage = "01010010\t" + toClientXmlMessage.Length + "\n10040000000000000000000000000000000000000000" + toClientXmlMessage;
myClientSocket.Send(Encoding.UTF8.GetBytes(toClientMessage));
}
}
catch (Exception ex)
{
//Console.WriteLine(ex.Message);
myClientSocket.Shutdown(SocketShutdown.Both);
myClientSocket.Close();
break;
}
}
}
}
}
3.这是一个我本地可以正常运行的代码,可能存在一些问题,希望大家多多指正。