C#实现TCP通讯(c#tcpclient接收数据)

C#实现TCP通讯(c#tcpclient接收数据)

编码文章call10242025-02-01 3:11:2213A+A-

一、创建TCP连接

using System.Net.Sockets;
using System.Threading;

public event EventHandler<TcpEventArgs> NewCodeEvent;
bool isRuning = false;
TcpListener tcpListener;
Socket clientSocket;
Thread threadListen;

public void TurnOn()
{
	isRuning = true;
	tcpListener = new TcpListener(IPAddress.Parse(localIp), localPort);
	tcpListener.Start();
	threadListen = new Thread(Listen);
	threadListen.Start();
}

public void TurnOff()
{
	isRuning = false;
	try
	{
		tcpListener.Stop();
	}
	catch (Exception)
	{
	}
}

二、监听数据

private void Listen()
{
	while (isRuning)
	{
		try
		{
			clientSocket = tcpListener.AcceptSocket();
			clientSocket.SendTimeout = 100;
			clientSocket.ReceiveTimeout = 10000;
			//监听到新的链接
			if (!clientSocket.RemoteEndPoint.ToString().Contains(deviceIp))
			{
				try
				{
					clientSocket.Disconnect(true);
				}
				catch (Exception)
				{
				}
				continue;
			}
			ReciveProcess();
		}
		catch (Exception ex)
		{
		}
	}
}

private void ReciveProcess()
{
	DateTime lastTime = DateTime.Now;
	while (isRuning)
	{
		Thread.Sleep(1000);
		bool ok = false;
		try
		{
			ok = ReadData(clientSocket);
		}
		catch (Exception)
		{

		}

		if (ok)
		{
			lastTime = DateTime.Now;
			continue;
		}
		if ((DateTime.Now - lastTime).TotalSeconds > 4)
		{
			lastTime = DateTime.Now;
			//设备长时间没有数据
			break;
		}
	}
	try
	{
		//强行关闭链
		clientSocket.Disconnect(true);
	}
	catch (Exception)
	{

	}
}

三、解析数据

private bool ReadData(Socket socket)
{
	Thread.Sleep(300);
	byte[] buffer = new byte[1024];
	int count = 0;
	try
	{
		count = socket.Receive(buffer, SocketFlags.None);
	}
	catch (Exception)
	{
	}
	if (count <= 0)
	{
		return false;
	}
	//有数据
	string str = "";
	str = Encoding.ASCII.GetString(buffer, 0, count);
	str = str.Replace("\r", "").Replace("?", "");
	//接收到的数据
	if (NewCodeEvent == null)
	{
		return true;
	}

	TcpEventArgs(this, e);
	return true;
}
点击这里复制本文地址 以上内容由文彬编程网整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

文彬编程网 © All Rights Reserved.  蜀ICP备2024111239号-4