当前位置:网站首页>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边栏推荐
- Torchvision loads the weight of RESNET except the full connection layer
- Flutter theme (skin) changes
- Express get request
- Using appbarlayout to realize secondary ceiling function
- 证券开户的优惠怎样才能得到?在线开户安全?
- Small program learning path 1 - getting to know small programs
- Interpretation of orientedrcnn papers
- Opencv learning notes -day3 (mat object and creation related operations mat:: clone(), mat:: copyto(), mat:: zeros(), mat:: ones(), scalar()...)
- Opencv learning notes-day14 drawing of image geometry (rect class rotatedrect class, rectangle drawing rectangle circle drawing circular function line drawing line function ellipse drawing elliptic fu
- Deep understanding of continuation principle
猜你喜欢

12. problem set: process, thread and JNI architecture

Rew acoustic test (III): generate test signal

Dart asynchronous task

Talk about the job experience of kotlin cooperation process

Rew acoustic test (II): offline test

Flink Exception -- No ExecutorFactory found to execute the application

Detailed explanation of pipline of mmdetection

C#访问MongoDB并执行CRUD操作

Baidu map JS browsing terminal

Opencv learning notes -day4 image pixel reading and writing operations (array traversal and pointer traversal implementation, uchar vec3b data type and mat class functions mat:: at(), mat:: ptr())
随机推荐
Get to know handler again
Opencv learning notes -day3 (mat object and creation related operations mat:: clone(), mat:: copyto(), mat:: zeros(), mat:: ones(), scalar()...)
Opencv learning notes -day 12 (ROI region extraction and inrange() function operation)
Treatment process record of Union Medical College Hospital (Dongdan hospital area)
So the toolbar can still be used like this? The toolbar uses the most complete parsing. Netizen: finally, you don't have to always customize the title bar!
ES6 learning path (III) deconstruction assignment
桂林 稳健医疗收购桂林乳胶100%股权 填补乳胶产品线空白
Talk about the kotlin cooperation process and the difference between job and supervisorjob
Generate directory in markdown
C accesses mongodb and performs CRUD operations
Opencv learning notes-day14 drawing of image geometry (rect class rotatedrect class, rectangle drawing rectangle circle drawing circular function line drawing line function ellipse drawing elliptic fu
Opencv learning notes -day1 (image reading display imread, imshow, namedwindow)
Based on svelte3 X desktop UI component library svelte UI
Using appbarlayout to realize secondary ceiling function
RPC understanding
Pytorch for former Torch users - Tensors
What kind of experience is it to develop a "grandson" who will call himself "Grandpa"?
Deep Learning with Pytorch- A 60 Minute Blitz
Rew acoustic test (II): offline test
Couldn't load this key (openssh ssh-2 private key (old PEM format))