.NET TCP协议之TcpClient与TcpListener交互

时间:2024-05-31 18:34:38

问题:手机某项功能服务需要采用TCP协议与第三方交互通信。需先在公司内部测试此功能。

原因:第三方没有任何消息返回,也没有客服提供服务。

解决方法:公司内部做一个TCP协议服务器端,根据外网ip+端口提供服务。只要有握手请求,就有返回。

方案:建立服务器端提供服务,客户端测试服务。

.NET TCP协议之TcpClient与TcpListener交互

一、服务器端代码:

using System.Net.Sockets;
using Server.Library;
namespace Server
{
class ServerTcpTime
{
private const int portNum = 100;

[STAThread]
static void Main(string[] args)
{
string receiveMessage = string.Empty;
string sendMessage = string.Empty;

bool done = false;
TcpListener listener = new TcpListener(portNum);
listener.Start();
while (!done)
{
try
{
Console.WriteLine("Waiting for connection...");
TcpClient client = listener.AcceptTcpClient();
Console.WriteLine("Connection accepted.");
NetworkStream ns = client.GetStream();

//接收信息
#region
byte[] receiveBuffer = new byte[client.ReceiveBufferSize];
ns.Read(receiveBuffer, 0, receiveBuffer.Length);//读取网络流中的数据
receiveMessage = Encoding.Default.GetString(receiveBuffer).Trim('\0');//转换成字符串
Console.WriteLine(string.Format("{1} 接收到客户端发来的信息:{0}", receiveMessage, DateTime.Now.ToString()));
LogHelper.WirteMsg2LogFile(string.Format("接收到客户端发来的信息:{0}", receiveMessage), "TcpServer");
#endregion

//回复信息
#region
sendMessage = "在" + DateTime.Now.ToString() + "收到信息。";
byte[] sendBuffer = Encoding.Default.GetBytes(sendMessage);
ns.Write(sendBuffer, 0, sendBuffer.Length);
ns.Flush();
LogHelper.WirteMsg2LogFile(string.Format("返回给客户端的信息:{0}", sendMessage), "TcpServer");
#endregion

ns.Close();
client.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}

listener.Stop();
}

}
}

二、客户端代码:

using System.Net.Sockets;
namespace Client
{
public class ClientTcpTime
{
private const int portNum = 100;//服务器端口,可以随意修改
private const string hostName = "127.0.0.1";//服务器地址,127.0.0.1指本机

[STAThread]
static void Main(string[] args)
{
string receiveMessage = string.Empty;
string sendMessage = string.Empty;
try
{
Console.Write("Try to connect to " + hostName + ":" + portNum.ToString() + "\r\n");
TcpClient client = new TcpClient(hostName, portNum);
NetworkStream ns = client.GetStream();

//发送消息
sendMessage = "客户端发送的消息";
byte[] sendBuffer = Encoding.Default.GetBytes(sendMessage);
ns.Write(sendBuffer, 0, sendBuffer.Length);
ns.Flush();

//接收回复
receiveMessage = string.Empty;
byte[] receiveBuffer = new byte[10240];
int receiveBufferLength = ns.Read(receiveBuffer, 0, receiveBuffer.Length);
receiveMessage = Encoding.Default.GetString(receiveBuffer).Trim('\0');//转换成字符串
Console.WriteLine(string.Format("{1} 接收到服务器的返回信息:{0}", receiveMessage, DateTime.Now.ToString()));

ns.Close();
client.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}

Console.ReadLine();//由于是控制台程序,故为了清楚的看到结果,可以加上这句
}

}
}