here is my code for the client
class Program
{
static void Main(string[] args)
{
string msg;
Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 999);
sck.Bind(ep);
byte[] msgbytes;
while (true)
{
msg = Console.ReadLine();
msgbytes = ASCIIEncoding.ASCII.GetBytes(msg);
sck.BeginSendTo(msgbytes, 0, msgbytes.Length, SocketFlags.None, ep, null, sck);
Console.WriteLine("sent");
}
}
void callBack(IAsyncResult result)
{
((Socket)result.AsyncState).EndSendTo(result);
}
}
}
and here is server code
class Program
{
static void Main(string[] args)
{
string msg;
Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint ep = new IPEndPoint(IPAddress.Any, 999);
sck.Bind(ep);
byte[] msgbytes = new byte[100];
EndPoint client = (EndPoint)ep;
int bytesrec;
while (true)
{
bytesrec = sck.ReceiveFrom(msgbytes, 0, msgbytes.Length, SocketFlags.None, ref client);
msg = ASCIIEncoding.ASCII.GetString(msgbytes);
Console.WriteLine("4");
}
}
}
}
The problem is no packet is ever received by the server when i try sending with the client. The "4" is never written, which confirms sck.receivefrom executed.
In your client code change the following:
Instead of sck.Bind(ep); use sck.Connect(ep);
and instead of
sck.BeginSendTo(msgbytes, 0, msgbytes.Length, SocketFlags.None, ep, null, sck);
use
sck.Send(msgbytes, msgbytes.Length, SocketFlags.None);
and it should work...
edit:
if you really need to use async send... you can do something like:
IAsyncResult asyncres = sck.BeginSendTo(msgbytes, 0, msgbytes.Length, SocketFlags.None, ep, null, sck);
sck.EndSendTo(asyncres);
Your server needs to listen at 0.0.0.0, as it is doing, otherwise you are into the area of platform dependence; and your client needs to bind to an external IP address, not just 127.0.0.1, otherwise it has no way of ever sending any packet out of the local host.
Related
I'm creating an async TCP Server that works kinda like a chat room, or at least it should. When a new client connects to the server he receives a welcome message and also everytime he sends a message, the server echos it back. It works well when only one client is connected, but when another one connects, he doesn't receive the welcome msg nor the echos.
Here's some of my code.
private void btn_startserver_Click(object sender, EventArgs e)
{
server = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp); //Populates the Server obj.
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 23);
server.Bind(iep);
server.Listen(5);
server.BeginAccept(new AsyncCallback(AcceptConn), server);
WriteOnLog("Waiting for incoming connections...");
Thread t1 = new Thread(() => verifyCon(server));
t1.Start();
}
public void AcceptConn(IAsyncResult iar)
{
Socket oldserver = (Socket)iar.AsyncState;
Socket client = oldserver.EndAccept(iar);
clientList.Add(client);
WriteOnLog("Connected to: " + client.RemoteEndPoint.ToString());
string stringData = "Connected Successfully\r\nWelcome to the Server\r\n";
byte[] message1 = Encoding.UTF8.GetBytes(stringData);
client.BeginSend(message1, 0, message1.Length, SocketFlags.None,
new AsyncCallback(SendData), client);
WriteOnClients(client.RemoteEndPoint.ToString(), "add");
}
void SendData(IAsyncResult iar)
{
Socket client = (Socket)iar.AsyncState;
int sent = client.EndSend(iar);
client.BeginReceive(data, 0, size, SocketFlags.None,
new AsyncCallback(ReceiveData), client);
}
void ReceiveData(IAsyncResult iar)
{
Socket client = (Socket)iar.AsyncState;
string curClient = client.RemoteEndPoint.ToString();
int recv = client.EndReceive(iar);
if (recv == 0)
{
client.Close();
WriteOnLog("Connection lost with " + curClient);
WriteOnClients(curClient, "remove");
WriteOnLog("Waiting for client...");
connectedClients.Remove(curClient);
server.BeginAccept(new AsyncCallback(AcceptConn), server);
return;
}
string receivedData = Encoding.ASCII.GetString(data, 0, recv);
WriteOnLog(receivedData);
byte[] message2 = Encoding.UTF8.GetBytes(receivedData);
client.BeginSend(message2, 0, message2.Length, SocketFlags.None,
new AsyncCallback(SendData), client);
}
After you handle the first incoming connection (EndAccept), you need to call BeginAccept again to accept the next connection.
Currently you call BeginAccept only during initialization, and when a client disconnects.
I'm doing an UDP server, I can receive data fine but I don't know how to store the endpoint to send data back.
The commentary at the ultimate line of SetupServer() is where i dont know how to get the EndPoint.
This is my server code:
static private byte[] buffer = new byte[1024];
static private Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
private const int port = 904;
static void Main(string[] args) {
SetupServer();
Console.ReadLine();
}
static private void SetupServer() {
Console.WriteLine($"{DateTime.Now}: Setting up server on {port}...");
EndPoint remoteEP = new IPEndPoint(IPAddress.Any, port);
serverSocket.Bind(remoteEP);
Console.WriteLine($"{DateTime.Now}: Server created successfully");
serverSocket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref remoteEP,BeginReceive, null);
//serverSocket.SendTo(buffer, 0, buffer.Length, SocketFlags.None, remoteEP);
}
static private void BeginReceive(IAsyncResult ar) {
int recv = serverSocket.EndReceive(ar);
byte[] dataBuf = new byte[recv];
Array.Copy(buffer, dataBuf, recv);
Console.WriteLine($"{DateTime.Now}: {Encoding.ASCII.GetString(dataBuf)}");
EndPoint remoteEP = new IPEndPoint(IPAddress.Any, port);
serverSocket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref remoteEP, BeginReceive, null);
}
I figure out how to do it. I replaced the serverSocket.EndReceive(ar) in the BeginReceive method to EndReceiveFrom(ar,ref epSender) and with that end point (epSender) i can call the BeginReceiveFrom method.
static private void SetupServer() {
Console.WriteLine($"{DateTime.Now}: Setting up server on {port}...");
EndPoint remoteEP = new IPEndPoint(IPAddress.Any, port);
serverSocket.Bind(remoteEP);
Console.WriteLine($"{DateTime.Now}: Server created successfully");
serverSocket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref remoteEP,BeginReceive, serverSocket);
}
static private void BeginReceive(IAsyncResult ar) {
EndPoint epSender = new IPEndPoint(IPAddress.Any, port);
int recv = serverSocket.EndReceiveFrom(ar,epSender);
byte[] dataBuf = new byte[recv];
Array.Copy(buffer, dataBuf, recv);
Console.WriteLine($"{DateTime.Now}: {Encoding.ASCII.GetString(dataBuf)}");
serverSocket.SendTo(dataBuf,epSender)
serverSocket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref remoteEP, BeginReceive, serverSocket);
}
I am trying to develop a C# UTP server in order to send a list of string sList. This is continuously filled by another thread. My aspected software behavior is to get a client on the network and send each information.
Here the method:
internal static void MyUDPSocket()
{
byte[] data = new byte[1024];
IPEndPoint ip = new IPEndPoint(IPAddress.Any, 9050);
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.Bind(ip);
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 9050);
EndPoint Remote = (EndPoint)(sender);
while (true)
{
if (sList.Count > 0)
{
try
{
data = Encoding.ASCII.GetBytes(sList[0]);
socket.SendTo(data, data.Length, SocketFlags.None, Remote);
sList.RemoveAt(0);
}
catch (FormatException e) { }
catch (System.ArgumentNullException en) { }
}
}
}
Anyway, when I launch the software, C# return an Exception (System.Net.Sockets.SocketException) on socket.SendTo(data, data.Length, SocketFlags.None, Remote) and it say that there is not a required address in the context.
You are creating a destination address with INADDR_ANY, with a port of 0. You can't do that.
I have an udp client server source on C# and now I have a problem: I test my source on localhost but it doesn't receive on long way connections for example a VPS to a client.
Client:
private static void StartListener()
{
bool done = false;
UdpClient listener = new UdpClient(listenPort);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
try
{
while (!done)
{
byte[] bytes = listener.Receive(ref groupEP);
Thread.Sleep(100);
byte[] dcbufresponse = new byte[512];
dcbufresponse = Encoding.ASCII.GetBytes("0xc00901");
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(ipaddresssv), 9052);
s.SendTo(dcbufresponse, dcbufresponse.Length, SocketFlags.None, ipep);
done = true;
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{
listener.Close();
}
}
Server :
private static Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
private static IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(ipnow), 9052);
s.SendTo(dcbuf, dcbuf.Length, SocketFlags.None, ipep);
Console.WriteLine("sended");
sended.Add(ipnow);
try
{
listener.Client.ReceiveTimeout = 5000;
byte[] bytes = listener.Receive(ref groupEP);
string dcresponse = Encoding.ASCII.GetString(bytes, 0, bytes.Length);
Console.WriteLine(dcresponse);
}
Problem is this : client doesn't receive anything and client can not send to server after receiving ...
Edit :
My Serve Have Two Ip Address !
and i thinking that i must bind once of my two ip address to my udp client :-?
do you think that its work ?
I've tried multiple methods of doing this, and non seem to work out. But there must be a way.
What I'm trying to do (in C#) is create a server. I want the server to listen on a IP and port, and when it connects to a client, I want it to read what the client says, and send a reply. For the client, I want to connect to a server and send data, and receive the reply from the server.
How can I go about doing this?
I've used Microsoft examples and examples found on MSDN. They have Client > data > Server but it doesn't ever seem to include the server reply.
I know this can be done, obviously, because we have multiplayer games.
Thanks for the help.
EDIT - Code snippets
SERVER
static void Main(string[] args)
{
int recv;
byte[] data = new byte[1024];
IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 904);
Socket newSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
newSocket.Bind(endPoint);
Console.WriteLine("Listening for connections...");
//LISTEN FOR CLIENT
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 904);
EndPoint tmpRemote = (EndPoint)sender;
//READ MESSAGE FROM CLIENT
recv = newSocket.ReceiveFrom(data, ref tmpRemote);
Console.WriteLine("Messaged received from: " + tmpRemote.ToString());
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
string welcome = "Welcome to server!";
data = Encoding.ASCII.GetBytes(welcome);
//SEND WELCOME REPLY TO CLIENT
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sock.Bind(tmpRemote);
sock.SendTo(data, tmpRemote);
Console.WriteLine("Reply sent to client");
while (true)
{
if(!newSocket.Connected)
{
Console.WriteLine("Client disconnected.");
break;
}
data = new byte[1024];
recv = newSocket.ReceiveFrom(data, ref tmpRemote);
if (recv == 0)
break;
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
}
newSocket.Close();
Console.WriteLine("Server disconnected.");
Console.ReadLine();
}
}
CLIENT
static void Main(string[] args)
{
Console.WriteLine("Message [127.0.0.1:904]: ");
string msg = Console.ReadLine();
byte[] packetData = ASCIIEncoding.ASCII.GetBytes(msg);
string IP = "127.0.0.1";
int port = 904;
IPEndPoint ep = new IPEndPoint(IPAddress.Parse(IP), port);
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
client.SendTo(packetData, ep);
Console.WriteLine("Data sent!");
int recv;
byte[] data = new byte[1024];
EndPoint tmpRemote = (EndPoint)ep;
while(true)
{
//READ MESSAGE FROM SERVER
recv = client.ReceiveFrom(data, ref tmpRemote);
Console.WriteLine("Messaged received from: " + tmpRemote.ToString());
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
}
client.Close();
Console.WriteLine("Client disconnected.");
Console.ReadLine();
}
I can't get the server to talk back to the client and have the client read/display the server's reply.
change this sentence
sock.SendTo(data, tmpRemote);
to
newSocket.SendTo(data, tmpRemote);
and remove these sentences, you have bind local EndPoint twice.
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sock.Bind(tmpRemote);
In Net, you can use UdpClient instead of Socket.
If you want a demo, look at this demo.