Search code examples
c#socketsxamarinresponse

How to manage response when trying to connect to a server?


I am new to socket stuff and i am just trying to connect to a server and getting a response. Here is my code :

IPEndPoint ipe = new IPEndPoint(address, port);
Socket tempSocket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
tempSocket.Connect(ipe);

So when i do that the server (delphi) is doing this:

Socket.SendText(#2+'D'+'ERRO GMT! Terminal '+Socket.RemoteAddress+' nao cadastrado.'+#3);

But i don't really know hot to receive that response after doing that socket.Connect. Is it possible to get that?


Solution

  • Here is a quick sample using TcpListener server + TcpClient. The asynchronous stuff looks much better on async function (not so much on console). client.GetStream().ReadAsync is reading the server response.

        public static void Main(string[] args)
        {
            // sample listener
            var listener = new TcpListener(IPAddress.Any, 1334);
            listener.Start ();
            listener.BeginAcceptTcpClient ((ar) => 
                {
                    var l = ar.AsyncState as TcpListener;
    
                    if (l != null)
                    {
                        var bytes = Encoding.UTF8.GetBytes ("Hello World!");
                        l.EndAcceptTcpClient (ar).GetStream ().Write (bytes, 0, bytes.Length);
                    }
                }, 
                listener);
    
            // async client
            var client = new TcpClient ();
    
            var connection = client.ConnectAsync("localhost", 1334);
    
            connection.Wait ();
    
            if (!connection.IsFaulted)
            {
                var buffer = new byte[1024];
                var res = client.GetStream ().ReadAsync (buffer, 0, buffer.Length);
                res.Wait ();
    
                if (!res.IsFaulted)
                {
                    Console.WriteLine (Encoding.UTF8.GetString (buffer));
                }
            }
        }