-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSocketServer.cs
More file actions
95 lines (75 loc) · 2.27 KB
/
SocketServer.cs
File metadata and controls
95 lines (75 loc) · 2.27 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
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SocketServerSample
{
public class SocketServer
{
Socket _socket;
private string ip;
private int port;
public SocketServer(int p)
{
ip = "0.0.0.0";
port = p;
}
public void Listen()
{
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipAddress = IPAddress.Parse(ip);
IPEndPoint iPEndPoint = new IPEndPoint(ipAddress, port);
_socket.Bind(iPEndPoint);
_socket.Listen(int.MaxValue);
Console.WriteLine($"监听{port}端口成功");
Thread thread = new Thread(SocketConnection);
thread.Start();
}
private void SocketConnection()
{
try
{
while (true)
{
var clientSocket = _socket.Accept();
Thread thread = new Thread(ReceiveMessage);
thread.Start(clientSocket);
}
}
catch (Exception ex)
{
}
}
private void ReceiveMessage(object socket)
{
Socket clientSocket = (Socket)socket;
Task.Factory.StartNew((obj) =>
{
while (true)
{
var input = Console.ReadLine();
var client = (Socket)obj;
client.Send(Encoding.UTF8.GetBytes(input));
}
}, clientSocket);
while (true)
{
try
{
byte[] buffer = new byte[1024];
var length = clientSocket.Receive(buffer);
Console.WriteLine($"客户端发送的消息:{Encoding.UTF8.GetString(buffer, 0, length)}");
}
catch (Exception ex)
{
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
break;
}
}
}
}
}