I’m implementing really simple UDP server in C# language.
When I implemented the server on Console based application, it worked well.
But when I implemented it by using the same code on Windows based application,
it doesn’t works as before.
I guessed that it is the problem of thread thing.
So I putted thread on the code, but still doesn’t works.
The function of “ReceiveFrom()” doesn’t works as before.
numReceived = udpSocket.ReceiveFrom(buffer, ref remoteEP);
what is a problem that I’m missing?
Thank you in advance.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace UDP_Server
{
public partial class Form1 : Form
{
private const int portNum = 5432;
Socket udpSocket;
byte[] buffer = new Byte[100];
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ThreadStart threadStart = new ThreadStart(onServer);
Thread thread = new Thread(threadStart);
thread.Start();
}
private void onServer()
{
EndPoint localEP = new IPEndPoint(IPAddress.Parse("xxx.xxx.xxx.xxx"), portNum);
//EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);
udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
udpSocket.Bind(localEP);
ThreadStart threadStart1 = new ThreadStart(OnReceive);
Thread thread1 = new Thread(threadStart1);
thread1.Start();
//udpSocket.BeginReceiveFrom(buffer, 0, buffer.Length,
//SocketFlags.None, ref remoteEP, new AsyncCallback(OnReceive), (object)this);
}
private void OnReceive()//IAsyncResult ar)
{
int numReceived = 0;
EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);
Console.WriteLine("UDP Starting Server");
Console.WriteLine("-----------------------------");
while (true)
{
numReceived = udpSocket.ReceiveFrom(buffer, ref remoteEP);
string s = Encoding.UTF8.GetString(buffer, 0, numReceived);
Console.WriteLine("Echo : {0}", s);
}
}
}
}
Looks as if your expecting it to print some output (which it is via the console window).You need to add all of the output you want to display in a windows forms control such as a rich text box and do: