473,404 Members | 2,114 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,404 software developers and data experts.

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?



Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.Net.Sockets;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using Joker.CardElem;
  6. using System.Data;
  7. using System.ComponentModel;
  8. using System.Text;
  9. using System.Threading;
  10.  
  11.  
  12. namespace Joker
  13. {
  14.     public class AsynchNetworkServer
  15.     {
  16.         class ClientHandler
  17.         {           
  18.             public ClientHandler(Socket socketForClient)
  19.             {
  20.                 socket = socketForClient;
  21.                 buffer = new byte[256];
  22.                 networkStream = new NetworkStream(socketForClient);
  23.                 callbackRead =  new AsyncCallback(this.OnReadComplete);
  24.                 callbackWrite = new AsyncCallback(this.OnWriteComplete);
  25.             }
  26.  
  27.             public void StartRead()
  28.             {
  29.                 networkStream.BeginRead(buffer, 0, buffer.Length, callbackRead, null);
  30.             }
  31.  
  32.             private void OnReadComplete(IAsyncResult ar)
  33.             {
  34.                 int bytesRead = networkStream.EndRead(ar);
  35.                 if (bytesRead > 0)
  36.                 {
  37.                     string s = System.Text.Encoding.ASCII.GetString(buffer, 0, bytesRead);
  38.                     Console.Write("Received {0} bytes from client: {1}" , bytesRead, s);
  39.  
  40.                     string[] level = s.Split(' ');
  41.  
  42.                     string quest = calcNext(int.Parse(level[0]), int.Parse(level[1])).ToString();                    
  43.  
  44.                     networkStream.BeginWrite(Encoding.ASCII.GetBytes(quest), 0, Encoding.ASCII.GetBytes(quest).Length, OnWriteComplete, networkStream);
  45.  
  46.                 }
  47.                 else
  48.                 {
  49.                     Console.WriteLine("Read connection dropped");
  50.                     networkStream.Close();
  51.                     socket.Close();
  52.                     networkStream = null;
  53.                     socket = null;
  54.                 }
  55.             }
  56.  
  57.             private void OnWriteComplete(IAsyncResult ar)
  58.             {
  59.                 networkStream.EndWrite(ar);
  60.                 Console.WriteLine("Write complete");
  61.  
  62.                 networkStream.BeginRead(buffer, 0, buffer.Length,callbackRead, null);                
  63.             }            
  64.  
  65.             private byte[] buffer;
  66.             private Socket socket;
  67.             private NetworkStream networkStream;
  68.             private AsyncCallback callbackRead;
  69.             private AsyncCallback callbackWrite;
  70.             private int pNum=0;
  71.             private JGame game = new JGame();
  72. }
  73.  
  74. public static void Main()
  75.         {
  76.             AsynchNetworkServer app = new AsynchNetworkServer();            
  77.             app.Run();
  78.         }
  79.  
  80.         private void Run()
  81.         {
  82.             // create a new TcpListener and start it up
  83.  
  84.             // listening on port 65000
  85.             TcpListener tcpListener = new TcpListener(8227);
  86.             tcpListener.Start();
  87.             Console.WriteLine("Listening For Clients!");
  88.             // keep listening until you send the file
  89.             for (; ; )
  90.             {
  91.                 // if a client connects, accept the connection
  92.                 // and return a new socket named socketForClient
  93.                 // while tcpListener keeps listening
  94.                 Socket socketForClient = tcpListener.AcceptSocket();
  95.                 if (socketForClient.Connected)
  96.                 {
  97.                     Console.WriteLine("Client connected");
  98.                     ClientHandler handler = new ClientHandler(socketForClient);
  99.                     handler.StartRead();
  100.                 }
  101.             }
  102.         }
  103.     }
Apr 1 '08 #1
7 4223
balabaster
797 Expert 512MB
Try changing:
Expand|Select|Wrap|Line Numbers
  1. public void StartRead(){
  2.   networkStream.BeginRead(buffer, 0, buffer.Length, callbackRead, null);
  3. }
To:
Expand|Select|Wrap|Line Numbers
  1. public void StartRead(){
  2.   networkStream.BeginRead(buffer, 0, buffer.Length, OnReadComplete, null);
  3. }
Apr 2 '08 #2
same thing...


BTW: Client code

Expand|Select|Wrap|Line Numbers
  1.  
  2. private NetworkStream streamToServer; 
  3.  
  4. public Client()
  5.         {
  6.             //outputC = "Connecting to {0}" + serverName;
  7.             TcpClient tcpSocket = new TcpClient("localhost", 8227);
  8.             streamToServer = tcpSocket.GetStream();
  9.         }
  10. public string reqDeal(string a)
  11.         {
  12.             StreamWriter writer = new StreamWriter(streamToServer);
  13.             writer.Write(a);
  14.             writer.Flush();
  15.  
  16.             StreamReader reader = new StreamReader(streamToServer);
  17.             string strResponse = reader.ReadLine();
  18.  
  19.             streamToServer.Close();
  20.  
  21.  
  22.             return strResponse;
  23.  
  24.         }
Apr 2 '08 #3
balabaster
797 Expert 512MB
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.
Apr 2 '08 #4
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".
Apr 2 '08 #5
balabaster
797 Expert 512MB
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?
Apr 2 '08 #6
Yes it does...

It displays on the console "Write Complete" and comes to the second networkStream.BeginRead(). then just sits there....
Apr 2 '08 #7
balabaster
797 Expert 512MB
Yes it does...

It displays on the console "Write Complete" and comes to the second networkStream.BeginRead(). 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.
Apr 2 '08 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: cmjman | last post by:
I have an issue where networkStream.Write doesn't perform its write downstream from my client program until the network stream is closed. I then see the data that was sent appear on the other side....
4
by: 0to60 | last post by:
I have a class that wraps a TcpClient object and manages all the async reading of the socket. It works really nice, and I use it all over the place. But there's this ONE INSTANCE where I create...
1
by: Casey Watson | last post by:
Hi :) I'm having some major trouble with an XML Client/Server application that I am writing. I am using NetworkStream with CryptoStream to Read and Write XML between computers. Now, whenever I...
1
by: Niels Johansen | last post by:
Hello, When using the asynchronous read method in the BufferedStream class, , it seems to me that it blocks like the normal synchronous read method. Why is it so? Why does the...
6
by: Ryan | last post by:
Hi, I am confused with how NetworkStream works. My application needs to handle heavy requests sent through TCP socket connection. I use NetworkStream.Read method to get the stream...
4
by: Kai Thorsrud | last post by:
Hi! How do i check: if "NetworkStream.Null = true then" it says .Null does not supports type Boolean Thanks /Kai
1
by: hamid_2020 | last post by:
I wrote a class to connect to a server using tcpclient. I need to connect to the server and the connection must be open.Then i need to send request to the server again and again.But the problem is...
3
by: shahla.saeed | last post by:
hi, plzz check my code and let me know where the problem is lying...becuase whenever i try to tansfer the file of 573KB(mp3) it just tranfer few Kb of file(Somtimes 5.2Kb,somtimes 32Kb..every time...
6
by: Pat B | last post by:
Hi, I'm writing my own implementation of the Gnutella P2P protocol using C#. I have implemented it using BeginReceive and EndReceive calls so as not to block when waiting for data from the...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.