如何获取所有连接客户端的TCP连接ID。实际上我在c#(控制台应用程序)中创建一个程序,该程序将返回带有连接客户端的连接ID和IMEI的阵列。下面的代码是简单的客户端和服务器程序,那么我怎样才能得到Connection id?
客户计划:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net.Sockets;
namespace TcpEchoClient
{
class TcpEchoClient
{
static void Main(string[] args)
{
Console.Title = "TCP Client";
String server = "xxx.xxx.x.xx"; // IP address
byte[] byteBuffer = Encoding.ASCII.GetBytes("Test Message");
int servPort = 1;
TcpClient client = null;
NetworkStream netStream = null;
try
{
client = new TcpClient(server, servPort);
Console.WriteLine("Connected to server... sending echo string");
netStream = client.GetStream();
netStream.Write(byteBuffer, 0, byteBuffer.Length);
Console.WriteLine("Sent {0} bytes to server...", byteBuffer.Length);
int totalBytesRcvd = 0;
int bytesRcvd = 0;
while (totalBytesRcvd < byteBuffer.Length)
{
if ((bytesRcvd = netStream.Read(byteBuffer, totalBytesRcvd, byteBuffer.Length - totalBytesRcvd)) == 0)
{
Console.WriteLine("Connection closed prematurely.");
break;
}
totalBytesRcvd += bytesRcvd;
}
Console.WriteLine("Received {0} bytes from server: {1}", totalBytesRcvd, Encoding.ASCII.GetString(byteBuffer, 0, totalBytesRcvd));
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
netStream.Close();
client.Close();
}
}
}
}
服务器程序:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
sing System.Net;
using System.Net.Sockets;
namespace TcpEchoServer
{
class TcpEchoServer
{
private const int BUFSIZE = 32;
static void Main(string[] args)
{
Console.Title = "TCP Server";
int servPort = 1;
TcpListener listener = null;
try
{
listener = new TcpListener(IPAddress.Any,servPort);
listener.Start();
}
catch(SocketException se)
{
Console.WriteLine(se.ErrorCode + ": " + se.Message);
Environment.Exit(se.ErrorCode);
}
byte[] rcvBuffer = new byte[BUFSIZE];
int bytesRcvd;
for (; ; )
{
TcpClient client = null;
NetworkStream netStream = null;
try
{
client = listener.AcceptTcpClient();
netStream = client.GetStream();
Console.Write("Handling client - ");
int totalBytesEchoed = 0;
while ((bytesRcvd = netStream.Read(rcvBuffer,0,rcvBuffer.Length)) >0)
{
netStream.Write(rcvBuffer,0,bytesRcvd);
totalBytesEchoed += bytesRcvd;
}
Console.WriteLine("echoed {0} bytes.", totalBytesEchoed);
netStream.Close();
client.Close();
}
catch(Exception e)
{
Console.WriteLine(e.Message);
netStream.Close();
}
}
}
}
}
有人能指出我正确的方向吗?
提前致谢。