## Socket C#
### Server - Winform Version
```csharp
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", SetLastError = true)]
public static extern int SendMessage(IntPtr hwnd, int msg, int wparam, int lparam);
TcpListener serverSocket = new TcpListener(8888);
TcpClient clientSocket = default(TcpClient);
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
delegate void appendStatusCallback(string text);
public void appendStatus(String v)
{
if (this.textBox1.InvokeRequired)
{
appendStatusCallback d = new appendStatusCallback(appendStatus);
this.Invoke(d, new object[] { v });
}
else
{
this.textBox1.AppendText(v+"\n");
}
}
private void StartServer()
{
int counter = 0;
serverSocket.Start();
appendStatus(" >> " + "Server Started");
counter = 0;
while (true)
{
counter += 1;
clientSocket = serverSocket.AcceptTcpClient();
//appendStatus(" >> " + "Client No:" + Convert.ToString(counter) + " started!");
handleClinet client = new handleClinet(this, serverSocket);
client.startClient(clientSocket, Convert.ToString(counter));
}
clientSocket.Close();
serverSocket.Stop();
appendStatus(" >> " + "exit");
Console.ReadLine();
}
Thread ThreadingServer = null;
private void button1_Click(object sender, EventArgs e)
{
ThreadingServer = new Thread(StartServer);
ThreadingServer.Start();
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
public class handleClinet
{
static Hashtable ht = new Hashtable();
Form1 form;
TcpListener serverSocket;
public handleClinet(Form1 form, TcpListener serverSocket)
{
this.form = form;
this.serverSocket = serverSocket;
}
TcpClient clientSocket;
Thread ctThread = null;
string clNo;
public void startClient(TcpClient inClientSocket, string clineNo)
{
this.clientSocket = inClientSocket;
this.clNo = clineNo;
ctThread = new Thread(doChat);
ctThread.Start();
}
static Dictionary GetParams(string uri)
{
var matches = Regex.Matches(uri, @"[\?&](([^&=]+)=([^&=#]*))", RegexOptions.Compiled);
var keyValues = new Dictionary(matches.Count);
foreach (Match m in matches)
keyValues.Add(Uri.UnescapeDataString(m.Groups[2].Value), Uri.UnescapeDataString(m.Groups[3].Value));
return keyValues;
}
private void doChat()
{
int requestCount = 0;
byte[] bytesFrom = new byte[10025];
string dataFromClient = null;
Byte[] sendBytes = null;
string serverResponse = null;
string rCount = null;
requestCount = 0;
while ((true))
{
try
{
requestCount = requestCount + 1;
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
//form.appendStatus(" >> " + "From client-" + clNo + dataFromClient);
//textBox1.AppendText(" >> " + "From client-" + clNo + dataFromClient);
//Invoke(DelegateTeste_ModifyText, "Server ready!");
// http://10.5.0.189:8888/?cmd=00001&time=20181023232359001$
Dictionary parameters = GetParams(dataFromClient);
string htKey = parameters["cmd"] + "_" + parameters["time"];
rCount = Convert.ToString(requestCount);
if (ht[htKey] == null)
{
ht.Add(htKey, htKey);
serverResponse = "clinet(" + clNo + ") " + rCount;
}
else
{
//serverResponse = "Skip clinet(" + clNo + ") " + rCount;
}
sendBytes = Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();
form.appendStatus(" >> " + serverResponse);
clientSocket.Close();
clientSocket.Dispose();
ctThread.Abort();
}
catch (Exception ex)
{
// form.appendStatus(" >> " + ex.ToString());
clientSocket.Close();
clientSocket.Dispose();
ctThread.Abort();
//serverSocket.Stop();
//serverSocket.Start();
//form.appendStatus(" >> " + "Re-Started");
}
}
}
}
}
```
### Server - Console Version
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
TcpListener serverSocket = new TcpListener(8888);
TcpClient clientSocket = default(TcpClient);
int counter = 0;
serverSocket.Start();
Console.WriteLine(" >> " + "Server Started");
counter = 0;
while (true)
{
counter += 1;
clientSocket = serverSocket.AcceptTcpClient();
Console.WriteLine(" >> " + "Client No:" + Convert.ToString(counter) + " started!");
handleClinet client = new handleClinet();
client.startClient(clientSocket, Convert.ToString(counter));
}
clientSocket.Close();
serverSocket.Stop();
Console.WriteLine(" >> " + "exit");
Console.ReadLine();
}
}
//Class to handle each client request separatly
public class handleClinet
{
TcpClient clientSocket;
Thread ctThread = null;
string clNo;
public void startClient(TcpClient inClientSocket, string clineNo)
{
this.clientSocket = inClientSocket;
this.clNo = clineNo;
ctThread = new Thread(doChat);
ctThread.Start();
}
private void doChat()
{
int requestCount = 0;
byte[] bytesFrom = new byte[10025];
string dataFromClient = null;
Byte[] sendBytes = null;
string serverResponse = null;
string rCount = null;
requestCount = 0;
while ((true))
{
try
{
requestCount = requestCount + 1;
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
Console.WriteLine(" >> " + "From client-" + clNo + dataFromClient);
rCount = Convert.ToString(requestCount);
serverResponse = "Server to clinet(" + clNo + ") " + rCount;
sendBytes = Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();
Console.WriteLine(" >> " + serverResponse);
clientSocket.Close();
clientSocket.Dispose();
ctThread.Abort();
}
catch (Exception ex)
{
Console.WriteLine(" >> " + ex.ToString());
clientSocket.Close();
clientSocket.Dispose();
ctThread.Abort();
}
}
}
}
}
```
### Client http Request
http://localhost:8888/?cmd=00001&time=20181023232359001$
http://localhost:8888/?cmd=00001&time=20181023232359002$
http://localhost:8888/?cmd=00001&time=20181023232359003$
### Client Winform
```csharp
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
//Declare and Initialize the IP Adress
// static IPAddress ipAd = IPAddress.Parse(GetLocalIPAddress());
static IPAddress ipAd = IPAddress.Parse("10.5.0.189");
//Declare and Initilize the Port Number;
static int PortNumber = 8888;
/* Initializes the Listener */
TcpListener ServerListener = new TcpListener(ipAd, PortNumber);
TcpClient clientSocket = default(TcpClient);
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void THREAD_MOD(string teste)
{
txtStatus.Text += Environment.NewLine + teste;
}
public static string GetLocalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
throw new Exception("No network adapters with an IPv4 address in the system!");
}
private void StartServer()
{
Action DelegateTeste_ModifyText = THREAD_MOD;
ServerListener.Start();
Invoke(DelegateTeste_ModifyText, "Server waiting connections!");
clientSocket = ServerListener.AcceptTcpClient();
Invoke(DelegateTeste_ModifyText, "Server ready!");
while (true)
{
byte[] bytesFrom;
string dataFromClient;
try
{
NetworkStream networkStream = clientSocket.GetStream();
bytesFrom = new byte[20];
networkStream.Read(bytesFrom, 0, 20);
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
if (dataFromClient.IndexOf("$") > -1 )
{
Console.WriteLine("test");
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
/* */
string serverResponse = "Received!";
Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();
Invoke(DelegateTeste_ModifyText, ".");
//MessageBox.Show(dataFromClient);
}
else
{
// continue;
}
}
catch(Exception ex)
{
//if (ex.InnerException != null)
//{
ServerListener.Stop();
ServerListener.Start();
Invoke(DelegateTeste_ModifyText, "Server waiting connections!");
clientSocket = ServerListener.AcceptTcpClient();
Invoke(DelegateTeste_ModifyText, "Server ready!");
//}
}
}
}
private void button1_Click(object sender, EventArgs e)
{
Thread ThreadingServer = new Thread(StartServer);
ThreadingServer.Start();
}
}
}
```
'etc' 카테고리의 다른 글
Gif Animation 배너 만들기 프로그램 (0) | 2019.07.30 |
---|---|
favorite 즐겨찾기 (0) | 2019.07.15 |
임시파일삭제 (0) | 2019.07.15 |
Amazon Web Service (0) | 2019.07.12 |
염창동둘레길 운동 평상시 운동 (0) | 2019.06.03 |
댓글