רשומות בנושאי מחשבים ותכנות #C
TCP Server: void server_foo(){ int port = 9050; int recv; byte[]data = new byte[1024]; IPEndPoint ipep = new IPEndPoint(IPAdress.Any, port); Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); newsock.Bind(ipep); newsock.Listen(10); Console.WriteLine("waiting for client..."); Socket client = newsoc.Accept(); IPEndPoint clientep = (IPEndPoint )client.RemoteEndPoint; Console.WriteLine($"Connected with {clientep.Address} at port {clientep.Port}"); data = Encoding.ASCII.GetBytes("[CONNECTED TO SERVER]"); client.Send(data, data.Length, SocketFlag.None); while (true) { try { data = new byte[1024]; recv = client.Receive(data); Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv)); if(recv == 0) break; // 0 == exit client.Send(data, recv, SocketFlags.None); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.ReadLine(); break; } finally { client.Close(); newsock.Close(); } } Console.WriteLine($"Disconnected from {clientep.Address}:{clientep.Port}"); }
TCP Client: void client_foo(){ byte[]data = new byte[1024]; string input, stringData; IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(ip), port); Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //try to connect: while (true) { try { server.Connect(ipep); Console.WriteLine("CONNECTED"); break; } catch { //try to reconnect: Console.WriteLine("Unable to connect: " + ex.Message); Console.WriteLine("Trying to reconnect in:"); for (int i = 1; i <= 5; i++) { Console.Write(i); Console.CursorLeft = 0; Thread.Sleep(1000); } } } // connected int recv = server.Receive(data); stringData = Encoding.ASCII.GetString(data, 0 ,recv); Console.WriteLine(stringData); while (true) { input = Console.ReadLine(); if (input == "exit") break; // send message server.Send(Encoding.ASCII.GetBytes(input)); // get message back data = new byte[1024]; recv = server.Receive(data); stringData = Encoding.ASCII.GetString(data, 0 ,recv); Console.WriteLine(stringData); } //close connection to server Console.WriteLine("Disconnected from server"); server.Shutdown(SocketShutdown.Both); server.Close(); }
אין תגובות:
הוסף רשומת תגובה