V
V
Vanes Ri_Lax2015-11-17 10:54:38
C++ / C#
Vanes Ri_Lax, 2015-11-17 10:54:38

How to read data through sockets?

Hello, I implemented a socket client in c#, the logic of work is as follows:
The client makes a request to the server, the server does something and returns a string to the client.
Here's how I did it:

Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress ipAddress = null;
            IPEndPoint Addr = null;

            ipAddress = Dns.GetHostEntry("web.domen.ru").AddressList[0];
            Addr = new IPEndPoint(ipAddress, 3319);
s.Connect(Addr);
byte[] outCommand = Encoding.UTF8.GetBytes("запрос на сервер");
s.Send(outCommand);
byte[] inCommand = new byte[s.Available];
s.Close();
string rzz = Encoding.UTF8.GetString(inCommand);

Why is there nothing in the variable rzz
Maybe I'm doing something wrong?
Thank you very much in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Makarov, 2015-11-17
@DmitryITWorksMakarov

you are not accepting an answer anywhere
instead
you need something like

var bytes = 0;
var sb= new StringBuilder();
var bytesReceived = new byte[256];
do 
{
    bytes = s.Receive(bytesReceived, bytesReceived.Length, 0);
    sb.Append(Encoding.UTF8.GetString(inCommand));
}
while (bytes > 0);
var rzz=sb.ToString();

Even better is to use asynchronous communication. Significant time may pass between the request and the response, and the response may not come at all. While waiting, the program can do something useful (instead of pretending to hang), such as waving the interface or accessing another server/socket.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question