-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathForm1.cs
More file actions
96 lines (85 loc) · 2.85 KB
/
Form1.cs
File metadata and controls
96 lines (85 loc) · 2.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
using System;
using System.Text;
using System.Text.Json;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace Server
{
public partial class Form1 : Form
{
private Socket sck,acp;
private Data[] users = new Data[0];
public Form1()
{
InitializeComponent();
}
private Socket Socket_Init() => new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
private void ListenButton_Click(object sender, EventArgs e)
{
sck=Socket_Init();
acp=Socket_Init();
string portNum=PortInput.Text;
try
{
sck.Bind(new IPEndPoint(0, Int32.Parse(portNum)));
sck.Listen(0);
}
catch
{
MessageBox.Show("Port Invalid");
}
new Thread(() =>
{
try
{
acp=sck.Accept();
sck.Close();
Read();
}
catch
{
MessageBox.Show("Disconnected");
Application.Exit();
}
}).Start();
}
private void Read()
{
while (true)
{
byte[]buffer= new byte[255];
int bufferSize = acp.Receive(buffer, 0, buffer.Length, SocketFlags.None);
if (bufferSize<=0)
throw new SocketException();
Array.Resize(ref buffer, bufferSize);
string data=Encoding.ASCII.GetString(buffer);
ServerRequest request=JsonSerializer.Deserialize<ServerRequest>(data);
if (request.requestType=="GET")
{
new Thread(() =>
{
ServerResponse response = new ServerResponse();
response.data=users[request.id];
response.response="HTTP/1.1 200 OK";
response.header="Content-Type:application/json";
string usersText = JsonSerializer.Serialize(response);
byte[] userSend=Encoding.ASCII.GetBytes(usersText);
acp.Send(userSend, 0, userSend.Length, SocketFlags.None);
}).Start();
}
else
{
Array.Resize(ref users, users.Length+1);
users[users.Length-1] = request.data;
Invoke((MethodInvoker)delegate
{
Names.Items.Add(request.data.name);
Ages.Items.Add(request.data.age);
});
}
}
}
}
}