473,706 Members | 2,293 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

UDP Async Server/Client Problem

1 New Member
Hello, I've just recently began network programming for c# (bought the book C# Network Programming) and I've ran into a few problems. Whenever I click the submit button on the client (to send the UDP packet to the UDP server), it doesn't work the first time (so it seems) and I must click it again to get the server to receive the packet and display it in a List Box. I was wondering if somone could help me track this problem down, I'm sure it's just something simple because I'm still very new to Network Programming. Here is my code:

UDP Server
Expand|Select|Wrap|Line Numbers
  1.  
  2. public partial class Form1 : Form
  3.     {       
  4.         private byte[] data = new byte[1024];
  5.         private int size = 1024;
  6.         private Socket server;          
  7.         public static IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
  8.         public static IPEndPoint sender2 = new IPEndPoint(IPAddress.Any, 0);
  9.         public static EndPoint sender3 = (EndPoint)sender2;
  10.  
  11.         public Form1()
  12.         {
  13.             CheckForIllegalCrossThreadCalls = false;
  14.             InitializeComponent();  
  15.             server = new Socket(AddressFamily.InterNetwork,
  16.             SocketType.Dgram, ProtocolType.Udp);     
  17.             server.Bind(iep);           
  18.             server.BeginReceive(data, 0, data.Length, SocketFlags.None, new AsyncCallback(connTest), server);
  19.         }
  20.  
  21.  
  22.         void connTest(IAsyncResult iar)
  23.         {
  24.             Socket client = (Socket)iar.AsyncState;
  25.  
  26.  
  27.             //Receive Data from Client
  28.  
  29.             string dataString;           
  30.             client.ReceiveFrom(data, ref sender3);
  31.             dataString = Encoding.ASCII.GetString(data);
  32.             results.Items.Add(dataString);         
  33.  
  34.  
  35.             data = new byte[1024];
  36.             int sent = client.EndReceive(iar);
  37.             server.BeginReceive(data, 0, data.Length, SocketFlags.None, new AsyncCallback(connTest), client);
  38.         }      
  39.  
  40.  
  41.     }
  42.  


UDP Client (Code was cut down a bit)
Expand|Select|Wrap|Line Numbers
  1.  
  2.   public partial class Form1 : Form
  3.     {
  4.         public static byte[] data = new byte[1024];
  5.         public static string stringData;
  6.         public static UdpClient server = new UdpClient("127.0.0.1", 9050);
  7.         public static IPEndPoint sender2 = new IPEndPoint(IPAddress.Any, 0);
  8.         public static Socket newSock = new Socket(AddressFamily.InterNetwork,
  9.                 SocketType.Dgram, ProtocolType.Udp);
  10.  
  11.  
  12. void sentData(IAsyncResult iar)
  13.         {
  14.             label5.Text = "Data Sent";
  15.         }
  16.  
  17.  
  18. private void submitText_Click(object sender, EventArgs e)
  19.         {
  20.             //data
  21.             data = new byte[1024];
  22.             data = Encoding.ASCII.GetBytes(input.Text);
  23.  
  24.             //Send message to server
  25.             server.BeginSend(data, data.Length, sentData, server);            
  26.         }
  27. }
  28.  
  29.  
  30.  
Any help would be appreciated!

Thanks.
Jun 12 '06 #1
1 9313
DMenT
1 New Member
Hello, I've just recently began network programming for c# (bought the book C# Network Programming) and I've ran into a few problems. Whenever I click the submit button on the client (to send the UDP packet to the UDP server), it doesn't work the first time (so it seems) and I must click it again to get the server to receive the packet and display it in a List Box. I was wondering if somone could help me track this problem down, I'm sure it's just something simple because I'm still very new to Network Programming. Here is my code:

UDP Server
Expand|Select|Wrap|Line Numbers
  1.  
  2. public partial class Form1 : Form
  3.     {       
  4.         private byte[] data = new byte[1024];
  5.         private int size = 1024;
  6.         private Socket server;          
  7.         public static IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
  8.         public static IPEndPoint sender2 = new IPEndPoint(IPAddress.Any, 0);
  9.         public static EndPoint sender3 = (EndPoint)sender2;
  10.  
  11.         public Form1()
  12.         {
  13.             CheckForIllegalCrossThreadCalls = false;
  14.             InitializeComponent();  
  15.             server = new Socket(AddressFamily.InterNetwork,
  16.             SocketType.Dgram, ProtocolType.Udp);     
  17.             server.Bind(iep);           
  18.             server.BeginReceive(data, 0, data.Length, SocketFlags.None, new AsyncCallback(connTest), server);
  19.         }
  20.  
  21.  
  22.         void connTest(IAsyncResult iar)
  23.         {
  24.             Socket client = (Socket)iar.AsyncState;
  25.  
  26.  
  27.             //Receive Data from Client
  28.  
  29.             string dataString;           
  30.             client.ReceiveFrom(data, ref sender3);
  31.             dataString = Encoding.ASCII.GetString(data);
  32.             results.Items.Add(dataString);         
  33.  
  34.  
  35.             data = new byte[1024];
  36.             int sent = client.EndReceive(iar);
  37.             server.BeginReceive(data, 0, data.Length, SocketFlags.None, new AsyncCallback(connTest), client);
  38.         }      
  39.  
  40.  
  41.     }
  42.  


UDP Client (Code was cut down a bit)
Expand|Select|Wrap|Line Numbers
  1.  
  2.   public partial class Form1 : Form
  3.     {
  4.         public static byte[] data = new byte[1024];
  5.         public static string stringData;
  6.         public static UdpClient server = new UdpClient("127.0.0.1", 9050);
  7.         public static IPEndPoint sender2 = new IPEndPoint(IPAddress.Any, 0);
  8.         public static Socket newSock = new Socket(AddressFamily.InterNetwork,
  9.                 SocketType.Dgram, ProtocolType.Udp);
  10.  
  11.  
  12. void sentData(IAsyncResult iar)
  13.         {
  14.             label5.Text = "Data Sent";
  15.         }
  16.  
  17.  
  18. private void submitText_Click(object sender, EventArgs e)
  19.         {
  20.             //data
  21.             data = new byte[1024];
  22.             data = Encoding.ASCII.GetBytes(input.Text);
  23.  
  24.             //Send message to server
  25.             server.BeginSend(data, data.Length, sentData, server);            
  26.         }
  27. }
  28.  
  29.  
  30.  
Any help would be appreciated!

Thanks.
The problem I've seen in your code is the following:

client.ReceiveF rom(data, ref sender3);

In this line you are attemping to read from the client socket, but at this point you already have a message in the data Byte array.

You could put a breakpoint at this line and watch the value for the data variable to se the behavior I am trying to explain.

Sorry for my bad english, I hope my comments let you some help.

Kind Regards,
DMenT.
Oct 26 '06 #2

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

Similar topics

1
2420
by: Ben | last post by:
I've written a fair amount of sockets code using the Winsock2 API, but I am having some trouble converting to the .Net Sockets API, specifically asynchronous sockets. What I have is a form that is both a client and a server. When the form starts I create a listening socket and call Socket.BeginAccept(). When a client connects my accept function is called, and it is on a separate thread. After I accept the client connection I connect to...
6
10451
by: Vanessa | last post by:
I have a question regarding async mode for calling Microsoft.XMLHTTP object. Microsoft.XMLHTTP hangs the IE once in a while suddenly, but it will work again after half an hour or so without doing anything. I have searched through the Internet and seems like the reason it hangs the browser it's because XMLHTTP limits you to two concurrent HTTP connections to each remote host; so if more than 2 concurrent connections strike the script...
6
3816
by: Shak | last post by:
Hi all, Three questions really: 1) The async call to the networkstream's endread() (or even endxxx() in general) blocks. Async calls are made on the threadpool - aren't we advised not to cause these to block? 2) You can connect together a binaryreader to a networkstream:
7
2855
by: Shak | last post by:
Hi all, I'm trying to write a thread-safe async method to send a message of the form (type)(contents). My model is as follows: private void SendMessage(int type, string message) { //lets send the messagetype via async NetworkStream ns = client.GetStream(); //assume client globally accessible
7
5075
by: =?Utf-8?B?Q2FybG8gRm9saW5p?= | last post by:
Hi, I implemented asynchronous calls to a web resource (using HttpWebRequest) from asp.net 2.0. The request it's made asyncronously (I see that beginGetResponse returns immediately). The number of worker thread and completionPortThreads are over 300. Making 200 calls I see that 100 are queued. There's a counter telling how much async calls are handled? How can I raise the number of request handled?
15
8402
by: dennis.richardson | last post by:
Greetings all. Here's a problem that's been driving me nuts for the last 48 hours. I'm hoping that someone has come across this before. I have a C# Application that reads a UDP broadcast (asynchronously). Then it repackages these UDP packets and sends them to a subscriber via TCP. Now, I can read the UDP stream all day long without the application
10
4502
by: Frankie | last post by:
It appears that System.Random would provide an acceptable means through which to generate a unique value used to identify multiple/concurrent asynchronous tasks. The usage of the value under consideration here is that it is supplied to the AsyncOperationManager.CreateOperation(userSuppliedState) method... with userSuppliedState being, more or less, a taskId. In this case, the userSuppliedState {really taskId} is of the object type,...
3
2685
by: Ryan Liu | last post by:
Will TcpClient.GetStream().Read()/ReadByte() block until at least one byte of data can be read? In a Client/Server application, what does it mean at the end of stream/no more data available? Client could send data once few seconds of minutes. Is there an "end" at all? In a C/S application, if server side call BeginginRead() again in EndRead() to create a endless loop to get message from client, is this a better approach than "one...
1
20633
by: Ryan Liu | last post by:
Hi, I have a 100 clients/ one server application, use ugly one thread pre client approach. And both side user sync I/O. I frequently see the error on server side(client side code is same, but I don't see the error): "System.IO.IOException: Unable to read data from the transport connection:A blocking operation was interrupted by a call to WSACancelBlockingCall"
1
1970
by: =?Utf-8?B?TWFyaw==?= | last post by:
Hi... There are a few questions wrapped up in this, but the main one is that the WebService.MyMethodAsync() methods that are automatically generated in the client code by VS 2005 don't seem to be finishing for me. We have a VS add-in written in .net that used to make a number of database calls to fill forms. To improve security, we moved the db calls to a web service and return DataSets for the calls (the result sets are always...
0
8696
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9285
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9050
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8993
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7906
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5938
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4448
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
2500
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2094
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.