c# udp client-server echo program - c#

I just started socket programming in c#. I wanted to develop a simple client-server echo application. The problem I encountered is when i try to echo the message back to the client, it does not receive it. I spent a lot of time searching for solution on variety of forums but i couldn't find any that would help me with my problem.
Thanks in advance.
Andrew
Here is the code:
Server:
static void Main(string[] args)
{
string data = "";
UdpClient server = new UdpClient(8008);
IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, 0);
Console.WriteLine(" S E R V E R IS S T A R T E D ");
Console.WriteLine("* Waiting for Client...");
while (data != "q")
{
byte[] receivedBytes = server.Receive(ref remoteIPEndPoint);
data = Encoding.ASCII.GetString(receivedBytes);
Console.WriteLine("Handling client at " + remoteIPEndPoint + " - ");
Console.WriteLine("Message Received " + data.TrimEnd());
server.Send(receivedBytes, receivedBytes.Length,remoteIPEndPoint);
Console.WriteLine("Message Echoed to" + remoteIPEndPoint + data);
}
Console.WriteLine("Press Enter Program Finished");
Console.ReadLine(); //delay end of program
server.Close(); //close the connection
}
}
Client:
static void Main(string[] args)
{
string data = "";
byte[] sendBytes = new Byte[1024];
byte[] rcvPacket = new Byte[1024];
UdpClient client = new UdpClient();
IPAddress address = IPAddress.Parse(IPAddress.Broadcast.ToString());
client.Connect(address, 8008);
IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, 0);
Console.WriteLine("Client is Started");
Console.WriteLine("Type your message");
while (data != "q")
{
data = Console.ReadLine();
sendBytes = Encoding.ASCII.GetBytes(DateTime.Now.ToString() + " " + data);
client.Send(sendBytes, sendBytes.GetLength(0));
rcvPacket = client.Receive(ref remoteIPEndPoint);
string rcvData = Encoding.ASCII.GetString(rcvPacket);
Console.WriteLine("Handling client at " + remoteIPEndPoint + " - ");
Console.WriteLine("Message Received: " + rcvPacket.ToString());
}
Console.WriteLine("Close Port Command Sent"); //user feedback
Console.ReadLine();
client.Close(); //close connection
}

I was able to get this working by making the client talk directly to the server instead of broadcasting:
var serverAddress = "127.0.0.1"; // Server is on the local machine
IPAddress address = IPAddress.Parse(serverAddress);
...unless I'm missing an important reason why you were using broadcast in your original code?

Related

C# TCP Chat Working On Localhost But Message Is 0 Or Null On Other IP Addresses?

So my TCP C# client server, an oddity is happening, when the server sends a message to a client running on localhost 127.0.0.1, the message goes through no problem, but when sending the message to a client running on another IPv4, the client and server connect but the message is received as null or zero. I am wondering why the message would come through no problem on localhost, but connect and then recieve a null message on a different ip though they connect?
Server code:
{
{
{
try
{
IPAddress ipAd = IPAddress.Parse(IPV4.Text); //use local m/c IP address, and use the same in the client
/* Initializes the Listener */
TcpListener myList = new TcpListener(ipAd, 8001);
/* Start Listeneting at the specified port */
myList.Start();
MessageBox.Show("The server is running at port 8001...");
MessageBox.Show("The local End point is :" + myList.LocalEndpoint);
MessageBox.Show("Looking for other computer");
Socket s = myList.AcceptSocket();
Console.WriteLine("Found buddy " + s.RemoteEndPoint);
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes(satt.Text));
MessageBox.Show("The message " + satt.Text + " was sent to the computer with IP address " + IPV4.Text);
byte[] b = new byte[100];
int k = s.Receive(b);
for (int i = 0; i < k; i++)
Console.Write(Convert.ToChar(b[i]));
void ServerStart()
{
TcpListener listener = new TcpListener(IPAddress.Any, 8001);
listener.Start();
Console.WriteLine("Listening on port: 8001");
while (true)
{
TcpClient client = listener.AcceptTcpClient();
ThreadPool.QueueUserWorkItem(state => HandleConnection(client));
void HandleConnection(TcpClient client)
{
Socket s = myList.AcceptSocket();
Console.WriteLine("Found buddy " + s.RemoteEndPoint);
Console.WriteLine("Number of connected buddies: " + connectedbuddies++);
client.Close();
string buddylist = myList.ToString();
socketlist = s.ToString();
slist = char.Parse(socketlist);
foreach (char slist in buddylist)
{
void HandleConnection(TcpClient client)
{
TcpListener myList = new TcpListener(ipAd, 8001);
/* Start Listeneting at the specified port */
myList.Start();
Console.WriteLine("Found buddy " + s.RemoteEndPoint);
while (connectedbuddies > 1)
{
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes(satt.Text));
}
}
Console.WriteLine("Number of connected buddies: " + connectedbuddies++);
client.Close();
}
}
Client code:
try
{
TcpClient tcpclnt = new TcpClient();
tcpclnt.Connect(RecieveIPAdd.Text, 8001); // use the ipaddress as in the server program
MessageBox.Show("Connected");
Stream stm = tcpclnt.GetStream();
MessageBox.Show("Listening for information......");
byte[] bb = new byte[100];
int k = stm.Read(bb, 0, 100);
string atk = Encoding.UTF8.GetString(bb.AsSpan(0, k));
Console.WriteLine($"Connected to server at IPv4 address {RecieveIPAdd.Text} Attack command Received: {atk}.
Thank you so much, I don't know why this would happen on an IP that is not localhost?

C# Winforms using TcpListener I can't connect to server from other devices on my LAN

I have a Winforms application that's going to transfers data to an Android application, for now it accepts a connection and displays a line of text as output. I tested on my local machine using the telnet command in PowerShell and it returns the correct message. When I tried the command from another PC on my network, it just times out and fails to connect. I made sure the port was free and that my firewall was turned off.
Here is my method:
public void senddata()
{
new Thread(() =>
{
Thread.CurrentThread.IsBackground = true;
TcpListener server = null;
try
{
Int32 port = 4296;
IPAddress localAddr =IPAddress.Any;
server = new TcpListener(localAddr, port);
server.Start();
Byte[] bytes = new Byte[256];
while (true)
{
server.Start();
Debug.WriteLine("Waiting for a connection... ");
TcpClient client = server.AcceptTcpClient();
NetworkStream stream = client.GetStream();
Debug.WriteLine("Connected!");
server.Stop();
while (stream.Read(bytes, 0, bytes.Length) != 0)
{
string data = "CPU: " + cpuCircle.Value + " C" + " | GPU: " + gpuCircle.Value + " C";
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
stream.Write(msg, 0, msg.Length);
stream.Flush();
}
client.Close();
}
}
catch (SocketException m)
{
Debug.WriteLine("SocketException: "+m);
}
finally
{
server.Stop();
}
}).Start();
}
Any idea what I'm doing wrong?
I think the main issue is that your listener object is being created in Thread itself due to which only first client able to connect. Please make TcpListener object before calling senddata() method and this listener should accept connection before calling senddata() method as well and pass client object to senddata(TcpClient client) method. By doing so you would be able to entertain theoretically unlimited clients simultanously:
Try This:
void StackOverflow4() // Your calling method
{
TcpListener server = null;
Int32 port = 4296;
IPAddress localAddr = IPAddress.Any;
try
{
server = new TcpListener(localAddr, port);
server.Start();
Byte[] bytes = new Byte[256];
while (true)
{
Debug.WriteLine("Waiting for a connection... ");
TcpClient client = server.AcceptTcpClient();
senddata(client);
}
}
catch (SocketException m)
{
Debug.WriteLine("SocketException: " + m);
//Some logic to restart listner
}
catch(Exception ex)
{
Debug.WriteLine(ex.Message);
//Some logic to restart listner
}
}
public void senddata(TcpClient client)
{
new Thread(() =>
{
Thread.CurrentThread.IsBackground = true;
try
{
Byte[] bytes = new Byte[256];
while (true)
{
NetworkStream stream = client.GetStream();
Debug.WriteLine("Connected!");
//server.Stop();
while (stream.Read(bytes, 0, bytes.Length) != 0)
{
string data = "CPU: " + cpuCircle.Value + " C" + " | GPU: " + gpuCircle.Value + " C";
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
stream.Write(msg, 0, msg.Length);
stream.Flush();
}
client.Close();
}
}
catch (SocketException m)
{
Debug.WriteLine("SocketException: " + m);
}
finally
{
//server.Stop();
}
}).Start();
}

Exception in opening a socket at my IP address

I am new in socket programming C#. I am trying to make a chat server between two computers but I am unable to do that because I cant start my Socket..... I gave the Server Program my IP address but gives me an exception... "The requested address is not valid in its context" ...Here is the code:
IPAddress hostIPAddress = IPAddress.Parse("178.189.27.85");
TcpListener serverSocket = new TcpListener(hostIPAddress, 8888);
int requestCount = 0;
TcpClient clientSocket = default(TcpClient);
serverSocket.Start();
Console.WriteLine(" >> Server Started");
clientSocket = serverSocket.AcceptTcpClient();
Console.WriteLine(" >> Accept connection from client");
requestCount = 0;
while ((true))
{
try
{
requestCount = requestCount + 1;
NetworkStream networkStream = clientSocket.GetStream();
byte[] bytesFrom = new byte[10025];
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
Console.WriteLine(" >> Data from client - " + dataFromClient);
string serverResponse = "Last Message from client" + dataFromClient;
Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();
Console.WriteLine(" >> " + serverResponse);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
clientSocket.Close();
serverSocket.Stop();
Console.WriteLine(" >> exit");
Console.ReadLine();
Client program
try {
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("Connecting.....");
tcpclnt.Connect("192.168.128.1",8888);
// use the ipaddress as in the server program
Console.WriteLine("Connected");
Console.Write("Enter the string to be transmitted : ");
String str=Console.ReadLine();
Stream stm = tcpclnt.GetStream();
ASCIIEncoding asen= new ASCIIEncoding();
byte[] ba=asen.GetBytes(str);
Console.WriteLine("Transmitting.....");
stm.Write(ba,0,ba.Length);
byte[] bb=new byte[100];
int k=stm.Read(bb,0,100);
for (int i=0;i<k;i++)
Console.Write(Convert.ToChar(bb[i]));
tcpclnt.Close();
}
catch (Exception e) {
Console.WriteLine("Error..... " + e.StackTrace);
}
IPAddress hostIPAddress = IPAddress.Parse("178.189.27.85");
Is your computer actually on the public internet? I would expect your computer to have a private IP (eg 192.168.x.y, 172.16-32.x.y, 10.x.y.z) unless it is directly connected to your internet connection.
Assuming you're on Windows, use a Command Prompt and run ipconfig, or visit Control Panel and look for your network settings. On Windows 7 for instance it's in the Network and Sharing Center, under "Change adapter settings"; look for the active adapter, right click and choose "Status".
Once you find your local IP address, use that. Or you can use 0.0.0.0 as a wildcard address – in effect saying "Just accept connections from wherever, I don't care what my IP address is."

Server socket in Android, Client sockect C# not sending until socket close

I have a socket server in Android and a client Socket in C#. The socket stablish connection properly but the information is not sended until the socket is close. Ot seems that the information is in buffer and it is not sended until the resources must be released.
The server code is:
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
try {
serverSocket = new ServerSocket(SocketServerPORT);
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
info.setText("I'm waiting here: "+ serverSocket.getLocalPort());
}
});
while (true) {
socket = serverSocket.accept();
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
String messageFromClient = "";
//If no message sent from client, this code will block the program
messageFromClient = dataInputStream.readLine();
count++;
message += "#" + count + " from " + socket.getInetAddress()+ ":" + socket.getPort() + "\n" + "Msg from client: " + messageFromClient + "\n";
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
msg.setText(message);
}
});
And the client code is:
IPAddress host = IPAddress.Parse("192.168.1.129");
IPEndPoint hostep = new IPEndPoint(host, 8080);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
sock.Connect(hostep);
//sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, true);
}
catch (SocketException ex) {
Console.WriteLine("Problem connecting to host");
Console.WriteLine(e.ToString());
sock.Close();
return;
}
try
{
string theMessageToSend = "Que mierda es esta";
byte[] msg = Encoding.Unicode.GetBytes(theMessageToSend + "$");
sock.Send(msg);
//sock.Send(Encoding.ASCII.GetBytes("testing %"));
} catch (SocketException ex) {
Console.WriteLine("Problem sending data");
Console.WriteLine( e.ToString());
sock.Close();
return;
}
sock.Close();
I can not reach the line messageFromClient = dataInputStream.readLine(); in the server side until the sock.Close(); is executed in the client side.
Many thanks in advance!

Async StreamWriter read and write C#

I've been coding a chat program that is made of two parts: server and client. The server uses TcpListener to listen for incoming requests to join the server, and the client uses TcpClient that it uses to connect to the server, and send messages. So far I have the handshake that is the first message sent when the client connects - it contains the client's IP address and the nickname set. I don't know how to make the server to listen asynchronously, because if it's not async, then the chat will be client -> server -> client -> server whereas it needs to be connected to multiple clients at once, and receive multiple messages at once. My code so far is written synchronously:
Client:
public void StartClient(string serverIP)
{
ReadWrite rw = new ReadWrite();
string nick = rw.GetNick();
string handshakeContents = "HANDSHAKE:" + nick + ":" + GetIP();
Int32 serverPort = 1336; // yay
TcpClient client = new TcpClient(serverIP, serverPort);
Console.WriteLine("Sending initial handshake: {0}", handshakeContents);
Byte[] data = System.Text.Encoding.ASCII.GetBytes(handshakeContents); // Convert handshakeContents to Byte[]
NetworkStream stream = client.GetStream(); // Instantiate object "stream" for use in read/write
stream.Write(data, 0, data.Length); // Send handshakeContents in Byte[] to server
Console.WriteLine(" - Connecting to IlanChat Server on ip {0}", serverIP);
Thread.Sleep(1000); // sleep 1s
data = new Byte[256];
string responseHandshake = String.Empty; // response handshake from server
Int32 bytes = stream.Read(data, 0, data.Length); // Read handshake.
responseHandshake = System.Text.Encoding.ASCII.GetString(data, 0, bytes); // Decode from Byte[] to ASCII string
Console.WriteLine(" - Received response handshake: {0}", responseHandshake);
Console.WriteLine(" - Successfully connected to IlanChat server on IP {0}", serverIP); // display message
Thread.Sleep(2000);
Console.Clear();
List<string> messagesRecieved = new List<string>();
while(true)
{
Console.Clear();
foreach (string msg in messagesRecieved)
{
Console.WriteLine(msg);
}
Console.WriteLine();
Console.Write("Enter message: ");
string msgRaw = Console.ReadLine();
string sendMsg = nick + ": " + msgRaw;
data = new Byte[256];
data = System.Text.Encoding.ASCII.GetBytes(sendMsg);
stream.Write(data, 0, data.Length); // finish this async shit
}
}
Server:
List<string> clientIP = new List<string>();
List<string> clientNicks = new List<string>();
string responseHandshake = "hello";
Int32 serverPort = 1336;
IPAddress machineIP = IPAddress.Parse(GetIP());
Console.Clear();
Console.WriteLine(" - Starting IlanChat server on IP {0}", machineIP);
TcpListener server = null;
server = new TcpListener(machineIP, serverPort);
server.Start();
Byte[] buffer = new Byte[256];
String data = null;
Console.WriteLine("Successfully started IlanChat server!");
while (true) // first alpha - only one user at a time
{
Console.WriteLine();
Console.WriteLine("Waiting for connections..");
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("User connecting..");
Console.WriteLine("Receiving handshake data..");
data = null;
NetworkStream stream = client.GetStream();
int i;
while ((i = stream.Read(buffer, 0, buffer.Length)) != 0)
{
data = System.Text.Encoding.ASCII.GetString(buffer, 0, i);
Console.WriteLine("Received handshake data: {0}", data);
Console.WriteLine("Processing data.."); // sample handshake: - HANDSHAKE:nick:ip
string tempNick = data.Replace("HANDSHAKE:", "");
string[] userDetails = tempNick.Split(':'); // should store to 0:nick, 1:ip
Console.WriteLine("Received client nick: {0}", userDetails[0]);
Console.WriteLine("Received client IP: {0}", userDetails[1]);
break;
}
Thread.Sleep(1100); // sleep
buffer = System.Text.Encoding.ASCII.GetBytes(responseHandshake);
Console.WriteLine("Sending response handshake..");
stream.Write(buffer, 0, buffer.Length);
}
Is there a way to make the server accept multiple connections at once, and maintain them? And is there a way to make the client receive multiple messages at once and type while refreshing the messages?
You need to look at using threading (Task library, async/await) to do what you want. Try looking here:
https://codereview.stackexchange.com/questions/29000/c-console-chat-server-async-await-tcpclient-tcplistener-networkstream-asyn
To get you started, assuming the logic in your code is correct you want to split up the server/client, something like this:
static void RunServer()
{
List<string> clientIP = new List<string>();
List<string> clientNicks = new List<string>();
string responseHandshake = "hello";
Int32 serverPort = 1336;
IPAddress machineIP = IPAddress.Parse(GetIP());
Console.Clear();
Console.WriteLine(" - Starting IlanChat server on IP {0}", machineIP);
TcpListener server = null;
server = new TcpListener(machineIP, serverPort);
server.Start();
Byte[] buffer = new Byte[256];
String data = null;
Console.WriteLine("Successfully started IlanChat server!");
while (true) // first alpha - only one user at a time
{
Console.WriteLine();
Console.WriteLine("Waiting for connections..");
TcpClient client = server.AcceptTcpClient();
Task.Run(() => RunClient(client));
}
}
static void RunClient(TcpClient client)
{
Byte[] buffer = new Byte[256];
Console.WriteLine("User connecting..");
Console.WriteLine("Receiving handshake data..");
String data = null;
string responseHandshake = "hello";
NetworkStream stream = client.GetStream();
int i;
while ((i = stream.Read(buffer, 0, buffer.Length)) != 0)
{
data = System.Text.Encoding.ASCII.GetString(buffer, 0, i);
Console.WriteLine("Received handshake data: {0}", data);
Console.WriteLine("Processing data.."); // sample handshake: - HANDSHAKE:nick:ip
string tempNick = data.Replace("HANDSHAKE:", "");
string[] userDetails = tempNick.Split(':'); // should store to 0:nick, 1:ip
Console.WriteLine("Received client nick: {0}", userDetails[0]);
Console.WriteLine("Received client IP: {0}", userDetails[1]);
break;
}
Thread.Sleep(1100); // sleep
buffer = System.Text.Encoding.ASCII.GetBytes(responseHandshake);
Console.WriteLine("Sending response handshake..");
stream.Write(buffer, 0, buffer.Length);
}

Categories