当前位置:网站首页>Tclistener server and tcpclient client
Tclistener server and tcpclient client
2022-06-30 09:25:00 【LongtengGensSupreme】
Tcplistener The service side and tcpclient Client side usage
#region test tcp
#region tcplistener Server side
public static void Start()
{
// test tcplistener Server side
Thread thread = new Thread(new ThreadStart(StartTcpListening))
{
IsBackground = Environment.OSVersion.Platform != PlatformID.Unix
};
thread.Start();
// test tcpclient client
//Thread threadClient = new Thread(new ThreadStart(TestTCPClient))
//{
// IsBackground = Environment.OSVersion.Platform != PlatformID.Unix
//};
//threadClient.Start();
}
/// <summary>
/// Turn on httplistener Listener Service
/// </summary>
public static void StartTcpListening()
{
TcpListener tcpListener = null;
#region TcpListener Server side
try
{
while (true)
{
try
{
tcpListener = new TcpListener(IPAddress.Any, 5566);
//tcpListener.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
tcpListener.Start();//tcpListener.Start(100);100 Is to set the maximum number of connected clients
}
catch (Exception e)
{
Thread.Sleep(1000);// Listening service startup failed , Pause 1 Seconds before starting the listening service
}
try
{
while (true)
{
//try
//{
// Get connected clients
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 Multiple real-time read and write information
//ThreadPool.GetMaxThreads(out int nWorkThreads, out int nPortThreads);
//ThreadPool.GetAvailableThreads(out int nWorkAvailable, out int nPortAvailable);
//System.Diagnostics.Trace.WriteLine($" Worker threads maximum : {nWorkThreads}, You can use :{nWorkAvailable}---i/o Most threads : {nPortThreads}, You can use :{nPortAvailable}");
Thread thread = new Thread(ProcessTcpData)
{
IsBackground = true
};
thread.Start(client);
#endregion
#region Only single real-time read and write information
//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(); No need to close
//}
//catch (Exception e)
//{
//}
}
}
catch (Exception e)
{
}
}
}
catch (Exception e)
{
}
#endregion
#region Listen for all of the local 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)
// {
// // closed
// var socket0 = socketServer.Accept();
// byte[] vs = new byte[1024];
// int count = socket0.Receive(vs);
// // Hair
// 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($" Worker threads maximum : {nWorkThreads}, You can use :{nWorkAvailable}---i/o Most threads : {nPortThreads}, You can use :{nPortAvailable}");
}
}
catch (Exception e)
{
}
}
#endregion
#region tcpclient client
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)
{
// write in
senddata = $" Ha ha ha 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);
// read out
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($" Worker threads maximum : {nWorkThreads}, You can use :{nWorkAvailable}---i/o Most threads : {nPortThreads}, You can use :{nPortAvailable}");
Thread.Sleep(2000);
}
}
}
catch (Exception e)
{
System.Diagnostics.Trace.WriteLine(" TcpClient Exception: {0}", e.InnerException.Message);
//throw;
}
finally
{
tcpClient.Close();
}
}
#endregion
#region see
static void Main1(string[] args)
{
AutoResetEvent mainEvent = new AutoResetEvent(false);
// Print thread pool status information for the first time
PrintThreadPoolsInfo();
// Create a work process
ThreadPool.QueueUserWorkItem(new WaitCallback(fnWordThread), mainEvent);
// Print thread pool status information again
PrintThreadPoolsInfo();
// Wait for the thread operation to end
mainEvent.WaitOne(5000, false);
Console.Read();
}
// Function to print thread pool status
private static void PrintThreadPoolsInfo()
{
Console.WriteLine(" Check thread pool status :{0}", DateTime.Now.ToString("HH:mm:ss:fff"));
int nWorkThreads;// The maximum number of worker threads in a thread pool
int nPortThreads;// Asynchronous in the thread pool I/O The maximum number of threads
ThreadPool.GetMaxThreads(out nWorkThreads, out nPortThreads);
int nWorkAvailable;
int nPortAvailable;
ThreadPool.GetAvailableThreads(out nWorkAvailable, out nPortAvailable);
Console.WriteLine(" Worker threads maximum : {0}, You can use :{1}", nWorkThreads, nWorkAvailable);
Console.WriteLine(" asynchronous I/O Threads most :{0}, You can use :{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边栏推荐
- Wechat development tool (applet)
- Express の Hello World
- What are the SQL add / delete / modify queries?
- Tutorial for beginners of small programs day01
- Deeply understand the working principle of kotlin collaboration suspend (beginners can also understand it)
- Bottomsheetbehavior principle of realizing the home page effect of Gaode map
- Rew acoustic test (I): microphone calibration
- Esp32 things (II): sharpening the knife without mistaking firewood - make preparations before project development
- QT downloading files through URL
- Opencv learning notes -day2 (implemented by the color space conversion function cvtcolar(), and imwrite image saving function imwrite())
猜你喜欢

12. problem set: process, thread and JNI architecture

Use Huawei performance management service to configure the sampling rate on demand

Advanced technology management -- how managers design and build echelons

Bottomsheetbehavior principle of realizing the home page effect of Gaode map

Installation, use and explanation of vulnerability scanning tool OpenVAS

Maxiouassigner of mmdet line by line interpretation

Pytorch BERT

Flink Exception -- No ExecutorFactory found to execute the application

Talk about how the kotlin collaboration process establishes structured concurrency

桂林 稳健医疗收购桂林乳胶100%股权 填补乳胶产品线空白
随机推荐
JVM tuning related commands and explanations
Anchorgenerator for mmdet line by line interpretation
Small program learning path 1 - getting to know small programs
Express get request
Torchvision loads the weight of RESNET except the full connection layer
Agp7.0|kts makes a reinforced plug-in
Summary of Android knowledge points and common interview questions
Detailed explanation of rect class
Use V-IF with V-for
Influencing factors of echo cancellation for smart speakers
RPC understanding
Opencv learning notes-day9 opencv's own color table operation (colormap coloraptypes enumeration data types and applycolormap() pseudo color function)
Deep Learning with Pytorch- A 60 Minute Blitz
About MySQL Boolean and tinyint (1)
Linear-gradient()
Talking about the difference between kotlin collaboration and thread
Express file download
Bottomsheetbehavior principle of realizing the home page effect of Gaode map
Acquisition de 100% des actions de Guilin latex par Guilin Robust Medical pour combler le vide de la gamme de produits Latex
Find the number that appears only once in the array