如何向/从具有相同IP和IP的TCP客户端发送和接收同一端口多次(同时)并行 [英] How to send and receive to/from a TCP Client of same IP & same port multiple times (at the same time) in parallel
问题描述
在我的应用程序中,我有一个连接到tcp客户端的TCP侦听器。
在我的应用程序中有 数据列表&我想将数据发送到此客户端并多次并行地从客户端接收数据。
例如
List1有一些数据。 List2有一些数据。
发送List1&的数据。 List2同时在线程中的tcp客户端。
我怎么能得到它?
您好,
TCP通信的数据是流。你想要的是从服务器上的不同线程写入相同的流,然后尝试解析TCPclient端的流。 TCPClient发送一种类型的NetworkStream,并根据msdn doc:
https://docs.microsoft.com/en-us/dotnet/api/system.net.sockets.networkstream?view=netframework-4.7.2 ,
- NetworkStream不支持随机访问网络数据流。 CanSeek属性的值(表示流是否支持搜索)始终为false;
因此,您无法知道您所读取的List数据属于哪个线程to。b $ b您需要为每个要连接的List的数据创建一个新的TCPClient对象,然后使用BeginAcceptTcpClient()方法接收来自每个TCPclient对象的连接请求。创建一个线程以将一个List数据写入TCPclient。然后在异步回调中再次启用BeginAcceptTcpClient
,以递归方式接收来自多个客户端的访问请求。
代码示例:
使用System;
使用System.Collections.Generic;
使用System.IO;
使用System.Linq;
使用System.Net;
使用System.Net.Sockets;
使用System.Text;
使用System.Threading;
使用System.Threading.Tasks;
namespace TCPTest
{
class TCPServer
{
private static byte [] ListData = new byte [1024];
private const int port = 8088;
private static string IpStr =" 127.0.0.1" ;;
private static TcpListener服务器;
public static List< TcpClient> clients = new List< TcpClient>();
static void Main(string [] args)
{
IPAddress ip = IPAddress.Parse(IpStr);
IPEndPoint ip_end_point =新的IPEndPoint(ip,port);
// ============================================ =================
server = new TcpListener(ip_end_point);
server.Start();
Console.WriteLine(" Listener Succeed ...");
server.BeginAcceptTcpClient(new AsyncCallback(DoAcceptTcpclient),server);
Console.ReadKey();
}
private static void DoAcceptTcpclient(IAsyncResult ar)
{
//获取处理客户端请求的监听器。
TcpListener listener =(TcpListener)ar.AsyncState;
//结束操作并在
//控制台上显示收到的数据。
TcpClient client = listener.EndAcceptTcpClient(ar);
clients.Add(client);
//在此处理连接。 (将客户端添加到
//服务器表,读取数据等)
Console.WriteLine(" Client connected completed,id:{0}" client.Client.RemoteEndPoint.ToString ());
线程t =新线程(new ParameterizedThreadStart(ReceiveMessageFromClient));
t.Start(客户);
server.BeginAcceptTcpClient(new AsyncCallback(DoAcceptTcpclient),server);
}
private static void ReceiveMessageFromClient(object reciveClient)
{
TcpClient client = reciveClient as TcpClient;
if(client == null)
{
Console.WriteLine(" client error");
返回;
}
while(true)
{
try
{
NetworkStream stream = client.GetStream();
Console.WriteLine("等待数据......");
int num = stream.Write(ListData,0,ListData.Length);
if(num!= 0)
{
string str = Encoding.UTF8.GetString(result,0,num);
Console.WriteLine(" Data Lenth:{0},Data:{1}",num,str);
}
else
{
Console.WriteLine(" Client Closed");
休息;
}
}
catch(例外e)
{
clients.Remove(client);
Console.WriteLine(" error:" + e.ToString());
休息;
}
}
}
}
}
祝你好运,
Drake
Hi,
In my app i have a TCP listener which is connected to a tcp client.
In my app i have a list of data & i want to send data to this client and receive the data from client multiple times in parallel.
e.g
List1 has some data. List2 has some data.
send data of List1 & List2 at the same time to tcp client in thread.
how can i achive it?
Hello,
The data of TCP communication is stream. What you want is to write from different threads on the server to the same stream and then try to parse the stream on the TCPclient side. TCPClient send a type of NetworkStream, and according to msdn doc:
https://docs.microsoft.com/en-us/dotnet/api/system.net.sockets.networkstream?view=netframework-4.7.2,
- The NetworkStream does not support random access to the network data stream. The value of the CanSeek property, which indicates whether the stream supports seeking, is always false;
So you are not able to know which thread is the List data you read belong to.
You need to create a new TCPClient object for the data of each List to connect, then use the BeginAcceptTcpClient() method to receive connection requests from each TCPclient object. Create a thread to Write one of List data to TCPclient. Then enable BeginAcceptTcpClient again in the asynchronous callback to recursively receive access requests from multiple clients.Code Sample:
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; namespace TCPTest { class TCPServer { private static byte[] ListData = new byte[1024]; private const int port = 8088; private static string IpStr = "127.0.0.1"; private static TcpListener server; public static List<TcpClient> clients=new List<TcpClient>(); static void Main(string[] args) { IPAddress ip = IPAddress.Parse(IpStr); IPEndPoint ip_end_point = new IPEndPoint(ip, port); //============================================================= server = new TcpListener(ip_end_point); server.Start(); Console.WriteLine("Listener Succeed ..."); server.BeginAcceptTcpClient(new AsyncCallback(DoAcceptTcpclient), server); Console.ReadKey(); } private static void DoAcceptTcpclient(IAsyncResult ar) { // Get the listener that handles the client request. TcpListener listener = (TcpListener)ar.AsyncState; // End the operation and display the received data on // the console. TcpClient client = listener.EndAcceptTcpClient(ar); clients.Add(client); // Process the connection here. (Add the client to a // server table, read data, etc.) Console.WriteLine("Client connected completed,id:{0}",client.Client.RemoteEndPoint.ToString()); Thread t=new Thread(new ParameterizedThreadStart(ReceiveMessageFromClient)); t.Start(client); server.BeginAcceptTcpClient(new AsyncCallback(DoAcceptTcpclient), server); } private static void ReceiveMessageFromClient(object reciveClient) { TcpClient client = reciveClient as TcpClient; if (client == null) { Console.WriteLine("client error"); return; } while (true) { try { NetworkStream stream = client.GetStream(); Console.WriteLine("waiting for data..."); int num = stream.Write(ListData, 0, ListData.Length); if (num != 0) { string str = Encoding.UTF8.GetString(result,0,num); Console.WriteLine("Data Lenth:{0}, Data:{1}", num, str); } else { Console.WriteLine("Client Closed"); break; } } catch (Exception e) { clients.Remove(client); Console.WriteLine("error:" + e.ToString()); break; } } } } }
Best regards,
Drake
这篇关于如何向/从具有相同IP和IP的TCP客户端发送和接收同一端口多次(同时)并行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!