-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathServer.cs
51 lines (44 loc) · 1.68 KB
/
Server.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Server
{
class Server
{
static void Main(string[] args)
{
// 创建一个用于监听的Socket
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// 绑定IP地址和端口号
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 4323);
listener.Bind(localEndPoint);
object? buffsize = listener.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer);
Console.WriteLine(buffsize);
// 开始监听
Console.WriteLine("Waiting for a connection...");
listener.Listen(10);
while (true)
{
// 接受连接
Socket handler = listener.Accept();
Console.WriteLine($"Connected: {handler.RemoteEndPoint}");
// 读取数据
byte[] buffer = new byte[1024];
int bytesRec = handler.Receive(buffer);
string data = Encoding.ASCII.GetString(buffer, 0, bytesRec);
Console.WriteLine($"Received: {data}");
// 发送数据
byte[] msg = Encoding.ASCII.GetBytes("Hello from server!");
handler.Send(msg);
// 关闭连接
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
}
}