Tcplistener服务端与tcpclient客户端使用
作者:互联网
Tcplistener服务端与tcpclient客户端使用
#region 测试tcp
#region tcplistener服务端
public static void Start()
{
//测试tcplistener服务端
Thread thread = new Thread(new ThreadStart(StartTcpListening))
{
IsBackground = Environment.OSVersion.Platform != PlatformID.Unix
};
thread.Start();
//测试tcpclient客户端
//Thread threadClient = new Thread(new ThreadStart(TestTCPClient))
//{
// IsBackground = Environment.OSVersion.Platform != PlatformID.Unix
//};
//threadClient.Start();
}
/// <summary>
/// 开启httplistener监听服务
/// </summary>
public static void StartTcpListening()
{
TcpListener tcpListener = null;
#region TcpListener服务端
try
{
while (true)
{
try
{
tcpListener = new TcpListener(IPAddress.Any, 5566);
//tcpListener.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
tcpListener.Start();//tcpListener.Start(100);100是设置最大连接客户端数量
}
catch (Exception e)
{
Thread.Sleep(1000);//监听服务启动失败,暂停1秒之后再启动监听服务
}
try
{
while (true)
{
//try
//{
//获取连接的客户端
TcpClient client = tcpListener.AcceptTcpClient();//Socket socket = tcpListener.AcceptSocket();
//client.LingerState.Enabled = false;
string data = null;
byte[] bytes = new byte[1024];
NetworkStream stream = client.GetStream();
int i = stream.Read(bytes, 0, bytes.Length);
data = Encoding.Default.GetString(bytes, 0, i);
byte[] msg = Encoding.Default.GetBytes(data + "ok");
stream.Write(msg, 0, msg.Length);
stream.Flush();
#region 多个实时读取写入信息
//ThreadPool.GetMaxThreads(out int nWorkThreads, out int nPortThreads);
//ThreadPool.GetAvailableThreads(out int nWorkAvailable, out int nPortAvailable);
//System.Diagnostics.Trace.WriteLine($"辅助线程最多: {nWorkThreads},可用:{nWorkAvailable}---i/o线程最多: {nPortThreads},可用:{nPortAvailable}");
Thread thread = new Thread(ProcessTcpData)
{
IsBackground = true
};
thread.Start(client);
#endregion
#region 只能单个实时读取写入信息
//NetworkStream stream = client.GetStream();
//int i;
//while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
//{
// data = Encoding.Default.GetString(bytes, 0, i);
// System.Diagnostics.Trace.WriteLine("tcpListener Received: {0}", data);
// //byte[] msg = Encoding.Default.GetBytes(data + "ok");
// //stream.Write(msg, 0, msg.Length);
// //System.Diagnostics.Trace.WriteLine("Sent: {0}", data);
// byte[] msg = Encoding.Default.GetBytes(data + "-------ok");
// stream.Write(msg, 0, msg.Length);
// System.Diagnostics.Trace.WriteLine("tcpListener Sent: {0}", data);
//}
#endregion
//client.Close();不需要关闭
//}
//catch (Exception e)
//{
//}
}
}
catch (Exception e)
{
}
}
}
catch (Exception e)
{
}
#endregion
#region 监听本机的所有ip
//Socket socketServer = null;
//try
//{
// socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// socketServer.Bind(new IPEndPoint(IPAddress.Any, 7788));
// socketServer.Listen(10);
// //socketServer.LingerState.Enabled = false;
// while (true)
// {
// //收
// var socket0 = socketServer.Accept();
// byte[] vs = new byte[1024];
// int count = socket0.Receive(vs);
// //发
// byte[] vs1 = new byte[1024];
// socket0.Send(vs1);
// }
//}
//catch (Exception)
//{
// throw;
//}
//finally
//{
// socketServer.Close();
// //socketServer.Shutdown(SocketShutdown.Both);
//}
#endregion
}
public static void ProcessTcpData(object clientData)
{
try
{
TcpClient client = clientData as TcpClient;
NetworkStream stream = client.GetStream();
string data = null;
byte[] bytes = new byte[1024];
int i;
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = Encoding.Default.GetString(bytes, 0, i);
System.Diagnostics.Trace.WriteLine("tcpListener Received: {0}", data);
//byte[] msg = Encoding.Default.GetBytes(data + "ok");
//stream.Write(msg, 0, msg.Length);
//System.Diagnostics.Trace.WriteLine("Sent: {0}", data);
byte[] msg = Encoding.Default.GetBytes(data + "-------ok");
stream.Write(msg, 0, msg.Length);
System.Diagnostics.Trace.WriteLine("tcpListener Sent: {0}", data);
ThreadPool.GetMaxThreads(out int nWorkThreads, out int nPortThreads);
ThreadPool.GetAvailableThreads(out int nWorkAvailable, out int nPortAvailable);
System.Diagnostics.Trace.WriteLine($"辅助线程最多: {nWorkThreads},可用:{nWorkAvailable}---i/o线程最多: {nPortThreads},可用:{nPortAvailable}");
}
}
catch (Exception e)
{
}
}
#endregion
#region tcpclient客户端
public static void TestTCPClient()
{
TcpClient tcpClient = null;
try
{
//tcpClient = new TcpClient(new IPEndPoint(System.Net.Dns.Resolve(IPAddress.Any.ToString()).AddressList[0].Address, 7788));
tcpClient = new TcpClient();
tcpClient.Connect("127.0.0.1", 5566);
if (tcpClient.Connected)
{
String data = null;
int w = 0;
string senddata = null;
var stream = tcpClient.GetStream();
while (true)
{
//写入
senddata = $"哈哈哈kkkk2233--{++w}";
#if DEBUG
Console.WriteLine($"TcpClient Send: {senddata}");
#else
System.Diagnostics.Trace.WriteLine($"TcpClient Send: {senddata}");
#endif
byte[] sendBytes = Encoding.ASCII.GetBytes(senddata);
stream.Write(sendBytes, 0, sendBytes.Length);
//读出
byte[] receBytes = new byte[1024];
var rece = stream.Read(receBytes, 0, receBytes.Length);
data = Encoding.ASCII.GetString(receBytes, 0, rece);
#if DEBUG
Console.WriteLine($"TcpClient Received: {data}");
#else
System.Diagnostics.Trace.WriteLine($"TcpClient Received: {data}");
#endif
ThreadPool.GetMaxThreads(out int nWorkThreads, out int nPortThreads);
ThreadPool.GetAvailableThreads(out int nWorkAvailable, out int nPortAvailable);
Console.WriteLine($"辅助线程最多: {nWorkThreads},可用:{nWorkAvailable}---i/o线程最多: {nPortThreads},可用:{nPortAvailable}");
Thread.Sleep(2000);
}
}
}
catch (Exception e)
{
System.Diagnostics.Trace.WriteLine(" TcpClient Exception: {0}", e.InnerException.Message);
//throw;
}
finally
{
tcpClient.Close();
}
}
#endregion
#region 查看
static void Main1(string[] args)
{
AutoResetEvent mainEvent = new AutoResetEvent(false);
//首次打印线程池状态信息
PrintThreadPoolsInfo();
//创建一个工作进程
ThreadPool.QueueUserWorkItem(new WaitCallback(fnWordThread), mainEvent);
//再次打印线程池状态信息
PrintThreadPoolsInfo();
//等待线程操作结束
mainEvent.WaitOne(5000, false);
Console.Read();
}
//打印线程池状态的函数
private static void PrintThreadPoolsInfo()
{
Console.WriteLine("检查线程池状态:{0}", DateTime.Now.ToString("HH:mm:ss:fff"));
int nWorkThreads;//线程池中辅助线程的最大数目
int nPortThreads;//线程池中异步I/O线程的最大数目
ThreadPool.GetMaxThreads(out nWorkThreads, out nPortThreads);
int nWorkAvailable;
int nPortAvailable;
ThreadPool.GetAvailableThreads(out nWorkAvailable, out nPortAvailable);
Console.WriteLine("辅助线程最多: {0},可用:{1}", nWorkThreads, nWorkAvailable);
Console.WriteLine("异步I/O线程 最多:{0}, 可用:{1}", nPortThreads, nPortAvailable);
}
private static void fnWordThread(object objState)
{
FileStream fs = new FileStream(@"C:/test.txt", FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
for (int i = 0; i < 1000; i++)
{
string sMsg = string.Format("{0} {1} ", i + 1, DateTime.Now.ToString("HH:mm:ss:fff"));
sw.WriteLine(sMsg);
}
sw.Close();
sw.Dispose();
fs.Close();
fs.Dispose();
AutoResetEvent objEvent = (AutoResetEvent)objState;
objEvent.Set();
}
#endregion
#endregion
标签:tcpclient,WriteLine,int,Tcplistener,new,byte,data,服务端,out 来源: https://blog.csdn.net/LongtengGensSupreme/article/details/120527184