Add project files.

main
Yik Teng Hie 3 years ago
parent 2e5e9400ee
commit 457c742274

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.5.33103.201
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MultiThreadTCPServer", "MultiThreadTCPServer\MultiThreadTCPServer.csproj", "{7C366206-F583-4E04-9715-AA36E8FFB3A8}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{7C366206-F583-4E04-9715-AA36E8FFB3A8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7C366206-F583-4E04-9715-AA36E8FFB3A8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7C366206-F583-4E04-9715-AA36E8FFB3A8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7C366206-F583-4E04-9715-AA36E8FFB3A8}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {AB0227F1-F1EC-4BAB-B88B-D7B7DAB5E24E}
EndGlobalSection
EndGlobal

@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

@ -0,0 +1,2 @@
// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");

@ -0,0 +1,74 @@
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace MultiThreadTCPServer
{
class Server
{
TcpListener _server = null;
public Server(string ip, int port)
{
IPAddress localAddr = IPAddress.Parse(ip);
_server = new TcpListener(localAddr, port);
_server.Start();
StartListener();
}
private void StartListener()
{
try
{
while (true)
{
Console.WriteLine("Waiting for a connection...");
TcpClient client = _server.AcceptTcpClient();
Console.WriteLine("Connected!");
Thread t = new Thread(new ParameterizedThreadStart(HandleClient));
t.Start();
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
_server.Stop();
}
}
private void HandleClient(object? obj)
{
TcpClient client = (TcpClient)obj;
var stream = client.GetStream();
string imei = String.Empty;
string data = String.Empty;
Byte[] bytes = new Byte[256];
int i;
try
{
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
string hex = BitConverter.ToString(bytes);
data = Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine($"{data}: Received: {Thread.CurrentThread.ManagedThreadId}");
string str = "Hey Client!";
Byte[] reply = System.Text.Encoding.ASCII.GetBytes(str);
stream.Write(reply, 0, reply.Length);
Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}: Sent: {str}");
}
}
catch (Exception e)
{
Console.WriteLine("Exception: {0}", e.ToString());
client.Close();
}
}
}
}
Loading…
Cancel
Save