本文介绍了TCP发送者/接收者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好.
我对自己的实现有些怀疑.
我需要实现一些简单的TCP发送器/接收器.
在客户端,我创建了简单的类,该类的内部实现包含
TcpClient,该客户端定期连接到网络中的适当地址并获取数据的一部分,在获取此数据后,他将对此执行一些操作.

在服务器端,我有TcpListener和线程,在获取客户端之后,我会在其中定期接收TcpClient,它应该模拟部分数据并将其发送回客户端.
您可以在下面看到服务器代码:

Hello everyone.
I have some doubts about my realization.
I need to implement some simple TCP sender/receiver.
On client side , i created simple class , internal implementation of which contains
TcpClient, that client periodically connects to appropriate address in network and get some portion of data , after getting this data he performs some action on that.

On server side i had TcpListener and thread in which i periodically receive TcpClient, after getting client, it supposed to simulate some portion of data and send it back to client side.
Server code you can see below:

public class SharerImp2 : IDisposable
	{
		TcpListener _listener = null;
		Thread _mainThread = null;
		CancellationTokenSource _cts = null;

		public SharerImp2(string ip, int port)
		{
			IPAddress address;
			if (!IPAddress.TryParse(ip, out address))
				throw new ArgumentNullException("ip");

			_listener = new TcpListener(new IPEndPoint(address, port));
		}

		public void Start()
		{
			_cts = new CancellationTokenSource();

			_mainThread = new Thread(new ThreadStart(StartInternal));
			_mainThread.Name = "Listener thread";
			_mainThread.IsBackground = true;
			_mainThread.Start();
		}

		private void StartInternal()
		{
			_listener.Start();

			while (true)
			{
				if (_cts.IsCancellationRequested)
					break;

				TcpClient client = _listener.AcceptTcpClient();

				using (NetworkStream netStream = client.GetStream())
				{
					byte[] data= Common.CaptureScreenWinForms.CaptureInBytesRepresentation();
					netStream.Write(data, 0, data.Length);
					netStream.Flush();
				}
			}

			_listener.Stop();
		}

                ...... some stop method needs to be implemented.

		public void Dispose()
		{
			if (!_cts.IsCancellationRequested)
			{
				_cts.Cancel();
				_cts.Dispose();
			}
		}
	}



所以我的问题包括下一个:
1)每次建立与服务器的连接并获取部分数据对客户端来说是否合理?还是最好一次建立连接并定期检查数据可用性?

2)最好在服务器端接受客户端并在附加线程或ThreadPool中发送部分数据.

您的所有建议和想法都将被采纳;)



So my question consist of next:
1) Is it reasonable ,to client, every time to establish connection to server and get some portion of data? Or it would be better to establish connection one-time and periodically check for data availability??

2) It would be better to on server side accepting client and sending portion of data in additional thread or ThreadPool ??

All your suggestions and ideas will be taken ;)

推荐答案


这篇关于TCP发送者/接收者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 12:05