当前位置:网站首页>Tclistener server and tcpclient client use -- socket listening server and socketclient use
Tclistener server and tcpclient client use -- socket listening server and socketclient use
2022-06-30 09:25:00 【LongtengGensSupreme】
Tcplistener The service side and tcpclient Client side usage --Socket Monitoring server and Socketclient Client side usage
public static void Start()
{
// Turn on httplistener Listener Service
//Thread thread = new Thread(new ThreadStart(StartTcpListening))
//{
// IsBackground = Environment.OSVersion.Platform != PlatformID.Unix
//};
//thread.Start();
// Turn on Socket Listener Service
Thread thread = new Thread(new ThreadStart(StartSocketListening))
{
IsBackground = Environment.OSVersion.Platform != PlatformID.Unix
};
thread.Start();
// test
//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
}
/// <summary>
/// tcplistener Data processing received by the server
/// </summary>
/// <param name="clientData"></param>
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)
{
}
}
/// <summary>
/// test TCPClient
/// </summary>
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();
}
}
/// <summary>
/// Turn on Socket Listener Service
/// </summary>
public static void StartSocketListening()
{
Socket socketServer = null;
try
{
while (true)
{
try
{
socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socketServer.Bind(new IPEndPoint(IPAddress.Any, 7788));
socketServer.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
//socketServer.LingerState.Enabled = false;
socketServer.Listen(100);//socketServer.Listen(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)
{
// Get connected clients
Socket socket = socketServer.Accept();
socket.LingerState.Enabled = false;
string data = null;
byte[] bytes = new byte[1024];
int i = socket.Receive(bytes);
data = Encoding.Default.GetString(bytes, 0, i);
byte[] arrSendMsg = Encoding.UTF8.GetBytes(data + "ok");
socket.Send(arrSendMsg);
#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(ProcessSocketData)
{
IsBackground = true
};
thread.Start(socket);
#endregion
#region Only single real-time read and write information
//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);
//}
#endregion
}
}
catch (Exception e)
{
}
}
}
catch (Exception e)
{
}
}
/// <summary>
/// Socket Data processing received by the server
/// </summary>
/// <param name="clientData"></param>
public static void ProcessSocketData(object clientData)
{
try
{
Socket socketServer = clientData as Socket;
while (true)
{
try
{
byte[] serverRecMsg = new byte[1024];
int length = socketServer.Receive(serverRecMsg);
string strSRecMsg = Encoding.UTF8.GetString(serverRecMsg, 0, length);
socketServer.Send(Encoding.UTF8.GetBytes(strSRecMsg + "ok"));
//System.Diagnostics.Trace.WriteLine($"Socket Sent: {strSRecMsg}");
//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}");
serverRecMsg.DefaultIfEmpty();
}
catch (Exception e)
{
}
}
}
catch (Exception e)
{
}
}
/// <summary>
/// test Socketlient
/// </summary>
public static void TestSocketlient()
{
Socket socketClient = null;
try
{
//tcpClient = new TcpClient(new IPEndPoint(System.Net.Dns.Resolve(IPAddress.Any.ToString()).AddressList[0].Address, 7788));
socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//socketClient.Connect(new IPEndPoint(IPAddress.Any, 7788));
socketClient.Connect("127.0.0.1", 7788);
if (socketClient.Connected)
{
String data = null;
int w = 0;
string senddata = null;
while (true)
{
// write in
senddata = $" Ha ha ha kkkk2233--{++w}";
#if DEBUG
Console.WriteLine($"SocketClient Send: {senddata}");
#else
System.Diagnostics.Trace.WriteLine($"SocketClient Send: {senddata}");
#endif
byte[] sendBytes = Encoding.ASCII.GetBytes(senddata);
socketClient.Send(sendBytes);
// read out
byte[] receBytes = new byte[1024];
var rece = socketClient.Receive(receBytes);
data = Encoding.ASCII.GetString(receBytes, 0, rece);
#if DEBUG
Console.WriteLine($"SocketClient Received: {data}");
#else
System.Diagnostics.Trace.WriteLine($"SocketClient 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
{
socketClient.Shutdown(SocketShutdown.Both);
socketClient.Disconnect(true);
socketClient.Close();
}
}边栏推荐
- [cmake] make command cannot be executed normally
- Pytorch BERT
- Row column (vertical and horizontal table) conversion of SQL
- 7. know JNI and NDK
- Script summary
- Express の post request
- Esp32 things (x): other functions
- Rew acoustic test (II): offline test
- C accesses mongodb and performs CRUD operations
- 将线程绑定在某个具体的CPU逻辑内核上运行
猜你喜欢

Tutorial for beginners of small programs day01

Express file upload

Mmdet line by line deltaxywhbboxcoder

Esp32 things (3): overview of the overall system design

Rew acoustic test (VI): signal and measurement

Agp7.0|kts makes a reinforced plug-in

Deeply understand the working principle of kotlin collaboration suspend (beginners can also understand it)

Maxiouassigner of mmdet line by line interpretation
![[wechat applet] realize applet pull-down refresh and pull-up loading](/img/23/2668a3a36fd46f63732c753fd6f237.jpg)
[wechat applet] realize applet pull-down refresh and pull-up loading

Advanced technology management -- how managers design and build echelons
随机推荐
快应用中实现自定义抽屉组件
ES6 learning path (III) deconstruction assignment
QT downloading files through URL
Wechat development tool (applet)
Opencv learning notes -day13 pixel value statistics calculation of maximum and minimum values, average values and standard deviations (use of minmaxloc() and meanstddev() functions)
9.JNI_ Necessary optimization design
Opencv learning notes-day9 opencv's own color table operation (colormap coloraptypes enumeration data types and applycolormap() pseudo color function)
Applet learning path 2 - event binding
Flink sql -- No factory implements ‘org. apache. flink. table. delegation. ExecutorFactory‘.
Express - static resource request
[protobuf] protobuf generates cc/h file through proto file
桂林 穩健醫療收購桂林乳膠100%股權 填補乳膠產品線空白
Flink Exception -- No ExecutorFactory found to execute the application
Deep Learning with Pytorch- neural network
Invalid update: invalid number of sections. The number of sections contained in the table view after
Couldn't load this key (openssh ssh-2 private key (old PEM format))
Esp32 things (II): sharpening the knife without mistaking firewood - make preparations before project development
Detailed explanation of rect class
Deeply understand the working principle of kotlin collaboration suspend (beginners can also understand it)
JPA naming rules