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 -
-
public partial class Form1 : Form
-
{
-
private byte[] data = new byte[1024];
-
private int size = 1024;
-
private Socket server;
-
public static IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
-
public static IPEndPoint sender2 = new IPEndPoint(IPAddress.Any, 0);
-
public static EndPoint sender3 = (EndPoint)sender2;
-
-
public Form1()
-
{
-
CheckForIllegalCrossThreadCalls = false;
-
InitializeComponent();
-
server = new Socket(AddressFamily.InterNetwork,
-
SocketType.Dgram, ProtocolType.Udp);
-
server.Bind(iep);
-
server.BeginReceive(data, 0, data.Length, SocketFlags.None, new AsyncCallback(connTest), server);
-
}
-
-
-
void connTest(IAsyncResult iar)
-
{
-
Socket client = (Socket)iar.AsyncState;
-
-
-
//Receive Data from Client
-
-
string dataString;
-
client.ReceiveFrom(data, ref sender3);
-
dataString = Encoding.ASCII.GetString(data);
-
results.Items.Add(dataString);
-
-
-
data = new byte[1024];
-
int sent = client.EndReceive(iar);
-
server.BeginReceive(data, 0, data.Length, SocketFlags.None, new AsyncCallback(connTest), client);
-
}
-
-
-
}
-
UDP Client (Code was cut down a bit) -
-
public partial class Form1 : Form
-
{
-
public static byte[] data = new byte[1024];
-
public static string stringData;
-
public static UdpClient server = new UdpClient("127.0.0.1", 9050);
-
public static IPEndPoint sender2 = new IPEndPoint(IPAddress.Any, 0);
-
public static Socket newSock = new Socket(AddressFamily.InterNetwork,
-
SocketType.Dgram, ProtocolType.Udp);
-
-
-
void sentData(IAsyncResult iar)
-
{
-
label5.Text = "Data Sent";
-
}
-
-
-
private void submitText_Click(object sender, EventArgs e)
-
{
-
//data
-
data = new byte[1024];
-
data = Encoding.ASCII.GetBytes(input.Text);
-
-
//Send message to server
-
server.BeginSend(data, data.Length, sentData, server);
-
}
-
}
-
-
-
Any help would be appreciated!
Thanks.
1 9297
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 -
-
public partial class Form1 : Form
-
{
-
private byte[] data = new byte[1024];
-
private int size = 1024;
-
private Socket server;
-
public static IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
-
public static IPEndPoint sender2 = new IPEndPoint(IPAddress.Any, 0);
-
public static EndPoint sender3 = (EndPoint)sender2;
-
-
public Form1()
-
{
-
CheckForIllegalCrossThreadCalls = false;
-
InitializeComponent();
-
server = new Socket(AddressFamily.InterNetwork,
-
SocketType.Dgram, ProtocolType.Udp);
-
server.Bind(iep);
-
server.BeginReceive(data, 0, data.Length, SocketFlags.None, new AsyncCallback(connTest), server);
-
}
-
-
-
void connTest(IAsyncResult iar)
-
{
-
Socket client = (Socket)iar.AsyncState;
-
-
-
//Receive Data from Client
-
-
string dataString;
-
client.ReceiveFrom(data, ref sender3);
-
dataString = Encoding.ASCII.GetString(data);
-
results.Items.Add(dataString);
-
-
-
data = new byte[1024];
-
int sent = client.EndReceive(iar);
-
server.BeginReceive(data, 0, data.Length, SocketFlags.None, new AsyncCallback(connTest), client);
-
}
-
-
-
}
-
UDP Client (Code was cut down a bit) -
-
public partial class Form1 : Form
-
{
-
public static byte[] data = new byte[1024];
-
public static string stringData;
-
public static UdpClient server = new UdpClient("127.0.0.1", 9050);
-
public static IPEndPoint sender2 = new IPEndPoint(IPAddress.Any, 0);
-
public static Socket newSock = new Socket(AddressFamily.InterNetwork,
-
SocketType.Dgram, ProtocolType.Udp);
-
-
-
void sentData(IAsyncResult iar)
-
{
-
label5.Text = "Data Sent";
-
}
-
-
-
private void submitText_Click(object sender, EventArgs e)
-
{
-
//data
-
data = new byte[1024];
-
data = Encoding.ASCII.GetBytes(input.Text);
-
-
//Send message to server
-
server.BeginSend(data, data.Length, sentData, server);
-
}
-
}
-
-
-
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.
Sign in to post your reply or Sign up for a free account.
Similar topics |
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...
|
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...
|
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:
|
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
|
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?
| |
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
|
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,...
|
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...
|
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"
|
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...
|
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...
| |
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
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...
|
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...
|
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();...
|
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...
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
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...
| |