C# 通过TCP协议进行系统间通信

NetworkStream 在网络中进行传输的数据流,传输的数据必须传入数据流中,才能与svr端进行数据交互。
首先客户端先获取用于发送信息的流,然后将要发送的信息存入byte[] 数组中(数据必须是byte[] 才能够写入流中),最后就是写入传输的数据流,发送 

直接上客户端代码:

//设置TCP连接对象
TcpClient connection = new TcpClientWithTimeout("10.120.230.21", port, 5000).Connect();
Console.WriteLine("{0}----->{1}", connection.Client.LocalEndPoint, connection.Client.RemoteEndPoint);
NetworkStream stream = connection.GetStream();

String factoryName = this.grdVersionList.ActiveRow.Cells["FACTORYNAME"].Text;
String productSpecName = this.grdVersionList.ActiveRow.Cells["PRODUCTSPECNAME"].Text;
String modelType = this.grdVersionList.ActiveRow.Cells["MODELTYPE"].Text;
String version = this.grdVersionList.ActiveRow.Cells["VERSION"].Text;

//组装Json格式对象
string jsonMessage = "{\"FACTORYNAME\":\"" + factoryName + "\",\"PRODUCTSPECNAME\":\"" + productSpecName + "\",\"MODELTYPE\":\"" + modelType + "\",\"VERSION\":\"" + version + "\"}";
//将信息存入缓存中
byte[] to_send = Encoding.UTF8.GetBytes(jsonMessage);
stream.Write(to_send, 0, to_send.Length);
string rcdata = "";
while (true)
{
	try
	{
		byte[] readbuf = new byte[2048]; // you must allocate space first
		int datalen = connection.Available;
		stream.ReadTimeout = 90000; // 90 seconds timeout on the read
		stream.Read(readbuf, 0, datalen);
		rcdata = ASCIIEncoding.ASCII.GetString(readbuf).Substring(0, datalen);
		//收到Svr端回复后跳出死循环,否则在Timeout进入异常块后跳出死循环
		if (datalen > 0)
		{
			Console.WriteLine("receive:" + rcdata);
			break;
		}
	}
	catch (Exception ex)
	{
		ExceptionMsgBox.This.ShowMessageBox(MessageType.Warning, "服务器未响应;"+ex, this.Text);
		break;
	}
}
// 关闭连接
stream.Close();      
connection.Close();

Svr端代码

开启服务:

IPAddress ip = new IPAddress(new byte[] { 127, 1, 1, 1 });
TcpListener server = new TcpListener(ip, 8005);
server.Start();//服务端启动侦听
TcpClient client = server.AcceptTcpClient();//接受发起连接对象的同步方法

解包

NetworkStream dataStream=client.GetStream();
byte[] buffer=new byte[8192];
int dataSize=dataStream.Read(buffer,0,8192);
Console.write(Encoding.default.GetString(buffer,0,dataSize));

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值