C# Socket connection error - c#

I'm working with sockets in C# and I'm getting the following error:
A request to send or receive data was
disallowed because the socket is not
connected and (when sending on a
datagram socket using a sendto call)
no address was supplied
Here is the code that I'm executing:
private void HostSubscriberService()
{
IPAddress ipV4 = PublisherService.ReturnMachineIP();
var localEP = new IPEndPoint(ipV4, _port);
var server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
server.Bind(localEP);
StartListening(server);
}
private void StartListening(Socket server)
{
EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);
while (true)
{
var data = new byte[1024];
int recv = server.ReceiveFrom(data, ref remoteEP);
string messageSendFromClient = Encoding.ASCII.GetString(data, 0, recv);
MessageBox.Show(messageSendFromClient);
}
}
The error happens # int recv = server.ReceiveFrom(data, ref remoteEP);
I just need to listen for new incoming connections and then print the message that was sent from the new client.
I need it to work on the TCP protocol, because some of the messages will be > 1500 bytes
Thanks!

You need to .BeginAccept() before you can receive.
Here's a link with a sinple Asynchronous Socket Server example

ReceiveFrom() is for UDP, use Accept() and Receive() for TCP

Related

A socket Listener which listens but it doesn´t know the port of the Sender in C#

I´m trying to make a Windows Service which waits a conexion but not in a determinate port. It has to wait a conexion and then, get the port which the sender is trying to connect. The check if the port is free is done by me in the Sender part.
Listener:
Here is where I need help. I need to do something to don´t need a port to inicializate the conexion.
{
// Get Host IP Address that is used to establish a connection
// In this case, we get one IP address of localhost that is IP : 127.0.0.1
// If a host has multiple addresses, you will get a list of addresses
IPHostEntry host = Dns.GetHostEntry("localhost");
IPAddress ipAddress = host.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);
try
{
// Create a Socket that will use Tcp protocol
Socket listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
// A Socket must be associated with an endpoint using the Bind method
listener.Bind(localEndPoint);
// Specify how many requests a Socket can listen before it gives Server busy response.
// We will listen 10 requests at a time
listener.Listen(10);
Console.WriteLine("Waiting for a connection...");
Socket handler = listener.Accept();
// Incoming data from the client.
string data = null;
byte[] bytes = null;
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
//_installerProcess = (Process) BinarySerialization.Deserializate(bytes);
//Console.WriteLine("Proceso recibido");
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf("<EOF>") > -1)
{
break;
}
break;
}
{...}
Sender:
Here is where i check te port and where I send the data.
public static void StartClient(String toSend)
{
byte[] bytes = new byte[1024];
try
{
// Connect to a Remote server
// Get Host IP Address that is used to establish a connection
// In this case, we get one IP address of localhost that is IP : 127.0.0.1
// If a host has multiple addresses, you will get a list of addresses
IPHostEntry host = Dns.GetHostEntry("localhost");
IPAddress ipAddress = host.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, FreeTcpPort() );
// Create a TCP/IP socket.
Socket sender = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
// Connect the socket to the remote endpoint. Catch any errors.
try
{
// Connect to Remote EndPoint
sender.Connect(remoteEP);
Console.WriteLine("Socket connected to {0}",
sender.RemoteEndPoint.ToString());
// Encode the data string into a byte array.
byte[] msg = Encoding.ASCII.GetBytes(toSend);
// Send the data through the socket.
int bytesSent = sender.Send(msg);
// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
Console.WriteLine("Echoed test = {0}",
Encoding.ASCII.GetString(bytes, 0, bytesRec));
{...}
}
static int FreeTcpPort()
{
TcpListener l = new TcpListener(IPAddress.Loopback, 0);
l.Start();
int port = ((IPEndPoint)l.LocalEndpoint).Port;
l.Stop();
return port;
}

UDP Listener Server Fails To Capture Incoming Data

I have a device with IP X.X.X.X which is not on the same
network as my UDP Server.
This device with IP X.X.X.X is sending packets with UDP protocol to
my UDP Server.
Packets are sent to port 5000 of my UDP Server
WireShark is showing that my PC is receiving packets from the device.
2711 351.573764 X.X.X.X 10.0.0.4 UDP 83 57514 → 5000 Len=61
I want to capture the sent packets for processing.
The following code is being taken from this example Currently, the moment program hits Socket.BeginReceiveFrom, Console application closes.
I believe that I'm missing something extremely basic, but I'm not able to see it now, so anything, tips or suggestions would be welcomed.
static private Socket Socket;
static private byte[] Buffer = new byte[1024];
static void Main(string[] args)
{
StartServer();
}
static public void StartServer()
{
//Setup the socket and message buffer
Socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
Socket.Bind(new IPEndPoint(IPAddress.Any, 5000));
//Start listening for a new message.
EndPoint ClientEndPoint = new IPEndPoint(IPAddress.Any, 5000);
Socket.BeginReceiveFrom(Buffer, 0, Buffer.Length, SocketFlags.None, ref ClientEndPoint, Receiver, Socket);
}
static private void Receiver(IAsyncResult iar)
{
//Get the received message.
Socket ReceiveSocket = (Socket)iar.AsyncState;
EndPoint ClientEndPoint = new IPEndPoint(IPAddress.Any, 5000);
int MessageLength = ReceiveSocket.EndReceiveFrom(iar, ref ClientEndPoint);
byte[] localMsg = new byte[MessageLength];
Array.Copy(Buffer, localMsg, MessageLength);
//Start listening for a new message.
EndPoint NewClientEndPoint = new IPEndPoint(IPAddress.Any, 5000);
Socket.BeginReceiveFrom(Buffer, 0, Buffer.Length, SocketFlags.None, ref NewClientEndPoint, Receiver, Socket);
// Do something here
}

Calling Socket.Accept() Returns Type initialization error

I am creating a simple networking application that allows one client to connect to the host and sends and recieves data between the two in a while loop. I got most of my code from MSDN, however when I run it, right after Socket.Accept() is called, the form stops running and a TypeInitialization Error is raised. Here is my code:
public static void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new byte[1024];
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, HostingPort);
// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and
// listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
Socket handler = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Start listening for connections.
while (true)
{
Console.WriteLine("Waiting for a connection...");
// Program is suspended while waiting for an incoming connection.
handler = listener.Accept();
// An incoming connection needs to be processed.
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
byte[] trimmedData = new byte[bytesRec];
Array.Copy(bytes, trimmedData, bytesRec);
string data = Encoding.ASCII.GetString(bytes));
// Show the data on the console.
Console.WriteLine("Text received : {0}", data);
// Echo the data back to the client.
byte[] msg = Encoding.ASCII.GetBytes(foo);
handler.Send(msg);
}
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
catch (Exception) { }
}
This is the function that controls everything. Can you find the error, or if there is a proven way to complete this, I'm fine with starting over from scratch. Thank you in advance.

C# UDP Server talk with Client

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.

UDP multicasting. C#

I try to send message to all members of the group. Sender:
// Create socket
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
// Multicast IP-address
IPAddress ip = IPAddress.Parse("224.168.55.25");
// Join multicast group
s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip));
// TTL
s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 2);
// Create an endpoint
IPEndPoint ipep = new IPEndPoint(ip, 4567);
// Connect to the endpoint
s.Connect(ipep);
// Scan message
while (true)
{
byte[] buffer = new byte[1024];
string msg = Console.ReadLine();
buffer = Encoding.ASCII.GetBytes(msg);
s.Send(buffer, buffer.Length, SocketFlags.None);
if (msg.Equals("Bye!", StringComparison.Ordinal))
break;
}
// Close socket
s.Close();
Receiver:
// Create new socket
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
// Create IP endpoint
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 4567);
// Bind endpoint to the socket
s.Bind(ipep);
// Multicast IP-address
IPAddress ip = IPAddress.Parse("224.168.55.25");
// Add socket to the multicast group
s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip, IPAddress.Any));
// Receive messages
while (true)
{
byte[] data = new byte[1024];
s.Receive(data);
string str = System.Text.Encoding.ASCII.GetString(data, 0, data.Length);
Console.WriteLine(str.Trim());
if (str.Equals("Bye!", StringComparison.Ordinal))
{
break;
}
}
I don't uderstand why there is a lot of free space between messages when I print them to screen on the client side? Why loop in the Receiver program doesn't stop after receiveing message Bye!? How can I fix this problems?
Thank you very much!
You are creating a udp socket. Udp sockets are not connection oriented. So it just receives messages and has no idea about the state of the sender. Even if the sender socket closes, the receiver would keep on listening.
I hope I have understood your question correctly.
if (strData.Trim().Equals("Bye!", StringComparison.Ordinal))
{
Console.WriteLine("that's right");
break;
}
Socket.Receive() return the bytes received you should use the return value to generate the string, or you will get a string with the length of 1024 and Trim cannot handle it.
int len = s.Receive(data);
string str = System.Text.Encoding.ASCII.GetString(data, 0, len);

Categories

Resources