Asynchronous NetworkStream Problem...

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • littleIO
    New Member
    • Apr 2008
    • 5

    Asynchronous NetworkStream Problem...

    Hi,

    I'm stuck on a very simple problem and just cant seem to get around it, little help would be much appreciated.
    I have a server which listens, receives calls, processes them and sends back the results to clients.
    The code below makes the client application not to respond. Client can send data but is stuck in the process of waiting information back from the server.

    Any ideas?



    Code:
    using System;
    using System.Net.Sockets;
    using System.Collections.Generic;
    using System.IO;
    using Joker.CardElem;
    using System.Data;
    using System.ComponentModel;
    using System.Text;
    using System.Threading;
    
    
    namespace Joker
    {
        public class AsynchNetworkServer
        {
            class ClientHandler
            {           
                public ClientHandler(Socket socketForClient)
                {
                    socket = socketForClient;
                    buffer = new byte[256];
                    networkStream = new NetworkStream(socketForClient);
                    callbackRead =  new AsyncCallback(this.OnReadComplete);
                    callbackWrite = new AsyncCallback(this.OnWriteComplete);
                }
    
                public void StartRead()
                {
                    networkStream.BeginRead(buffer, 0, buffer.Length, callbackRead, null);
                }
    
                private void OnReadComplete(IAsyncResult ar)
                {
                    int bytesRead = networkStream.EndRead(ar);
                    if (bytesRead > 0)
                    {
                        string s = System.Text.Encoding.ASCII.GetString(buffer, 0, bytesRead);
                        Console.Write("Received {0} bytes from client: {1}" , bytesRead, s);
    
                        string[] level = s.Split(' ');
    
                        string quest = calcNext(int.Parse(level[0]), int.Parse(level[1])).ToString();                    
    
                        networkStream.BeginWrite(Encoding.ASCII.GetBytes(quest), 0, Encoding.ASCII.GetBytes(quest).Length, OnWriteComplete, networkStream);
    
                    }
                    else
                    {
                        Console.WriteLine("Read connection dropped");
                        networkStream.Close();
                        socket.Close();
                        networkStream = null;
                        socket = null;
                    }
                }
    
                private void OnWriteComplete(IAsyncResult ar)
                {
                    networkStream.EndWrite(ar);
                    Console.WriteLine("Write complete");
    
                    networkStream.BeginRead(buffer, 0, buffer.Length,callbackRead, null);                
                }            
    
                private byte[] buffer;
                private Socket socket;
                private NetworkStream networkStream;
                private AsyncCallback callbackRead;
                private AsyncCallback callbackWrite;
                private int pNum=0;
                private JGame game = new JGame();
    }
    
    public static void Main()
            {
                AsynchNetworkServer app = new AsynchNetworkServer();            
                app.Run();
            }
    
            private void Run()
            {
                // create a new TcpListener and start it up
    
                // listening on port 65000
                TcpListener tcpListener = new TcpListener(8227);
                tcpListener.Start();
                Console.WriteLine("Listening For Clients!");
                // keep listening until you send the file
                for (; ; )
                {
                    // if a client connects, accept the connection
                    // and return a new socket named socketForClient
                    // while tcpListener keeps listening
                    Socket socketForClient = tcpListener.AcceptSocket();
                    if (socketForClient.Connected)
                    {
                        Console.WriteLine("Client connected");
                        ClientHandler handler = new ClientHandler(socketForClient);
                        handler.StartRead();
                    }
                }
            }
        }
  • balabaster
    Recognized Expert Contributor
    • Mar 2007
    • 798

    #2
    Try changing:
    Code:
    public void StartRead(){
      networkStream.BeginRead(buffer, 0, buffer.Length, callbackRead, null);
    }
    To:
    Code:
    public void StartRead(){
      networkStream.BeginRead(buffer, 0, buffer.Length, OnReadComplete, null);
    }

    Comment

    • littleIO
      New Member
      • Apr 2008
      • 5

      #3
      same thing...


      BTW: Client code

      Code:
      private NetworkStream streamToServer; 
      
      public Client()
              {
                  //outputC = "Connecting to {0}" + serverName;
                  TcpClient tcpSocket = new TcpClient("localhost", 8227);
                  streamToServer = tcpSocket.GetStream();
              }
      public string reqDeal(string a)
              {
                  StreamWriter writer = new StreamWriter(streamToServer);
                  writer.Write(a);
                  writer.Flush();
      
                  StreamReader reader = new StreamReader(streamToServer);
                  string strResponse = reader.ReadLine();
                
                  streamToServer.Close();
      
      
                  return strResponse;
             
              }

      Comment

      • balabaster
        Recognized Expert Contributor
        • Mar 2007
        • 798

        #4
        Have you stepped through the server code to make sure it's getting the message the client sends and processes and sends the reply back to the client? Before we can determine that the client isn't getting the response we have to:

        a). Prove the client is actually sending the message
        b). Prove the server is receiving the message
        c). Prove the server is sending back a message

        If we can prove that all of these things are happening, only then can we really determine where the problem lies.

        Comment

        • littleIO
          New Member
          • Apr 2008
          • 5

          #5
          Well the client is able to send a message to the server and any process activated is properly completed on the Server side but when the time comes to send it back to the client, the client application just hungs.
          No errors messages come up. Nor does the server part seem to show any problems at that time.
          And well If i use socket.close(); i am able to complete the whole process but only once, as on the second send to the server the StreamWriter comes up with an error "Stream was not writable".

          Comment

          • balabaster
            Recognized Expert Contributor
            • Mar 2007
            • 798

            #6
            Originally posted by littleIO
            Well the client is able to send a message to the server and any process activated is properly completed on the Server side but when the time comes to send it back to the client, the client application just hungs.
            No errors messages come up. Nor does the server part seem to show any problems at that time.
            And well If i use socket.close(); i am able to complete the whole process but only once, as on the second send to the server the StreamWriter comes up with an error "Stream was not writable".
            But is the server getting to the point where it's attempting to send the message back to the client?

            Comment

            • littleIO
              New Member
              • Apr 2008
              • 5

              #7
              Yes it does...

              It displays on the console "Write Complete" and comes to the second networkStream.B eginRead(). then just sits there....

              Comment

              • balabaster
                Recognized Expert Contributor
                • Mar 2007
                • 798

                #8
                Originally posted by littleIO
                Yes it does...

                It displays on the console "Write Complete" and comes to the second networkStream.B eginRead(). then just sits there....
                Got ya - I've got a VB 2005 project that I wrote earlier last year that does this. Sadly I no longer have VB 2005 and I'm waiting for VB 2008 to upgrade it so I can go over my code and figure out why mine works and yours doesn't...and then convert my code to C#. I'll get back to you as quickly as I can, but it's gonna take me a few.

                Comment

                Working...