-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathCommunicator.cs
112 lines (67 loc) · 2.24 KB
/
Communicator.cs
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace Sudoku
{
class Communicator
{
Socket S1;
private byte[] buff;
private string buff_s;
public string Status;
public delegate void MethodDelegate();
public event MethodDelegate StatusChange;
public Communicator()
{
S1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Status = "";
buff = new byte[1024];
buff_s = "";
}
private void ChangeStatus(string newstatus)
{
Status = newstatus;
if (StatusChange != null) StatusChange();
}
public void Connect()
{
IPEndPoint EP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9991);
ChangeStatus("Connecting");
S1.Connect(EP);
string x = "Hello There!";
S1.Send(Encoding.ASCII.GetBytes(x));
S1.Disconnect(true);
ChangeStatus("Done!");
}
public void Listen()
{
S1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
ChangeStatus("Listening");
IPEndPoint EP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9991);
S1.Bind(EP);
S1.Listen(1);
S1.BeginAccept(new AsyncCallback(OnConnect), null);
}
private void OnConnect(IAsyncResult R)
{
Socket temp = S1.EndAccept(R);
S1.Close();
S1 = temp;
ChangeStatus("Connected");
S1.Send(Encoding.ASCII.GetBytes("Welcome"));
S1.BeginReceive(buff, 0, buff.Length, SocketFlags.None, new AsyncCallback(OnReceive), null);
}
private void OnReceive(IAsyncResult R)
{
for (int i = 0; buff[i] != 0; i++)
{
buff_s += ((char)buff[i]).ToString();
buff[i] = 0;
}
S1.BeginReceive(buff, 0, buff.Length, SocketFlags.None, new AsyncCallback(OnReceive), null);
// MethodDelegate D = new MethodDelegate(BufferUpdated);
}
}
}