comparison Test/RewritingTest/TCPListenerTest.cs @ 33:7575980bffc9

update
author riono <e165729@ie.u-ryukyu.ac.jp>
date Tue, 20 Apr 2021 18:42:17 +0900
parents Test/RewritingTest/TCPListener.cs@3a7a71ee8738
children
comparison
equal deleted inserted replaced
32:3a7a71ee8738 33:7575980bffc9
1 using System;
2 using System.Net;
3 using System.Net.Sockets;
4 using System.Threading;
5 using System.Threading.Tasks;
6
7 public class TCPListenerTest {
8
9 public static void Main() {
10 TCPListenerTest listenerTest = new TCPListenerTest();
11
12 TcpListener listener = new TcpListener(IPAddress.IPv6Any, 11000);
13 listener.Server.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, 0);
14
15 // 開始
16 listener.Start();
17
18 Thread thread = new Thread ( () => listenerTest.TCPListenerFunc(listener));
19 thread.Name = "test";
20 thread.Start();
21 }
22
23 void SocketInTask(TCPListenerTest listenerTest) {
24 // Thread thread = new Thread (listenerTest.TCPListenerFunc);
25 // thread.Start();
26 }
27
28
29 public void TCPListenerFunc(TcpListener server) {
30 //TcpListener server = null;
31 try {
32 // IPAddress localAddress = IPAddress.Parse("127.0.0.1");
33 //
34 // server = new TcpListener(IPAddress.IPv6Any, 11000);
35 // // ipv4/v6対応
36 // server.Server.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, 0);
37 //
38 // // 開始
39 // server.Start();
40
41 string data = null;
42 Byte[] bytes = new byte[256];
43
44 while (true) {
45 Console.Write("Waiting for a connection... ");
46
47 TcpClient client = server.AcceptTcpClient();
48 client.NoDelay = true;
49
50 IPEndPoint endPoint = (IPEndPoint) client.Client.RemoteEndPoint;
51 IPAddress ipAddress = endPoint.Address;
52 IPHostEntry hostEntry = Dns.GetHostEntry(ipAddress);
53 Console.WriteLine("host:" + hostEntry.HostName + " port:" + endPoint.Port);
54
55 data = null;
56
57 NetworkStream stream = client.GetStream();
58
59 int i;
60
61 // Loop to receive all the data sent by the client.
62 while ((i = stream.Read(bytes, 0, bytes.Length)) != 0) {
63 // Translate data bytes to a ASCII string.
64 data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
65 Console.WriteLine("Received: {0}", data);
66
67 // Process the data sent by the client.
68 data = data.ToUpper();
69
70 byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
71
72 // Send back a response.
73 stream.Write(msg, 0, msg.Length);
74 Console.WriteLine("Sent: {0}", data);
75 }
76
77 // Shutdown and end connection
78 client.Close();
79 }
80 } catch (SocketException e) {
81 Console.WriteLine("SocketException: {0}", e);
82 } finally {
83 server.Stop();
84 }
85 }
86 }