basic C# tcp/ip client help

MadJuggla9

2[H]4U
Joined
Oct 9, 2002
Messages
3,515
im building a simple client to connect to a server via a socket given a hostname and a port. When i click "Connect and Send" I am telling it to send the request (GET /index.html for instance) to the server, then display the servers reply in a textbox called textBoxOutput.

It seems that it works perfectly as long as i dont mess with the ReadLine(). I tried an alternative method by sending bytes to from and array as characters to see if that would solve it. My program still locks anytime i try and grab something from the server

here is the code for my button:
Code:
       private void buttonConnectSend_Click(object sender, EventArgs e)
        {
            //setup some variables
            String host = textBoxHost.Text;
            int port = 80;
            String request = textBoxSendString.Text;

            //setup connection to server and send request
            Socket connectionSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            connectionSocket.Connect(host, port);
            connectionSocket.Send(System.Text.Encoding.UTF8.GetBytes(request));


            //setup connection to receive bytes from server
            System.IO.StreamReader connectionRead = new System.IO.StreamReader(new NetworkStream(connectionSocket));
            while (connectionRead.Peek() > 0) {
                textBoxOutput.AppendText(connectionRead.ReadLine() + "\r\n");
            }

            connectionSocket.Close();

like i said, it locks up once it hits the readline marks:
- textBoxOutput.AppendText(connectionRead.ReadLine() + "\r\n");

if i try
- textBoxOutput.AppendText("Unrelated Text\r\n");
then it works everytime.

any ideas? I know the problem lies in the connection somewhere but im not sure where. I get no compilation errors.


edit:
tcp.jpg
 
If you aren't getting any errors showing up, then it is probably the order or how you're using the functions. Try to reorder the code and see if that helps.
 
The calls you're doing are going to block when they have no data to read. Are you sure you're getting data back? Specifically, have you sent "GET /\n", or just "GET /"? The prior should work; the latter won't.
 
additionally, you should split the fetch routine into it's own thread so as not to lock up the UI :)

--KK
 
it ended up being the darned "\r\n", now it works great.

once i get a few more basic elements down it will be threaded. i havent done threading with c# before, but ive done some java threading, so i shouldnt have too many problems.

Thanks
 
Back
Top