Mercurial > hg > Database > Christie-sharp
view 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 |
line wrap: on
line source
using System; using System.Net; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; public class TCPListenerTest { public static void Main() { TCPListenerTest listenerTest = new TCPListenerTest(); TcpListener listener = new TcpListener(IPAddress.IPv6Any, 11000); listener.Server.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, 0); // 開始 listener.Start(); Thread thread = new Thread ( () => listenerTest.TCPListenerFunc(listener)); thread.Name = "test"; thread.Start(); } void SocketInTask(TCPListenerTest listenerTest) { // Thread thread = new Thread (listenerTest.TCPListenerFunc); // thread.Start(); } public void TCPListenerFunc(TcpListener server) { //TcpListener server = null; try { // IPAddress localAddress = IPAddress.Parse("127.0.0.1"); // // server = new TcpListener(IPAddress.IPv6Any, 11000); // // ipv4/v6対応 // server.Server.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, 0); // // // 開始 // server.Start(); string data = null; Byte[] bytes = new byte[256]; while (true) { Console.Write("Waiting for a connection... "); TcpClient client = server.AcceptTcpClient(); client.NoDelay = true; IPEndPoint endPoint = (IPEndPoint) client.Client.RemoteEndPoint; IPAddress ipAddress = endPoint.Address; IPHostEntry hostEntry = Dns.GetHostEntry(ipAddress); Console.WriteLine("host:" + hostEntry.HostName + " port:" + endPoint.Port); data = null; NetworkStream stream = client.GetStream(); int i; // Loop to receive all the data sent by the client. while ((i = stream.Read(bytes, 0, bytes.Length)) != 0) { // Translate data bytes to a ASCII string. data = System.Text.Encoding.ASCII.GetString(bytes, 0, i); Console.WriteLine("Received: {0}", data); // Process the data sent by the client. data = data.ToUpper(); byte[] msg = System.Text.Encoding.ASCII.GetBytes(data); // Send back a response. stream.Write(msg, 0, msg.Length); Console.WriteLine("Sent: {0}", data); } // Shutdown and end connection client.Close(); } } catch (SocketException e) { Console.WriteLine("SocketException: {0}", e); } finally { server.Stop(); } } }