C# UDP Server Client not receiving each others messages? - c#

so for my UDP C# chat application, I have a server program which is intended to recieve a response by listening for the client to send it on Port 8001, when it recieves the acknolwedement from the client it is supposed to send a message back to the client. However, though the client and server both say they are listening for each other, the server always immediately reports that it sent the message to IP address 0.0.0.0, so they are not linking, below is the code to the client and server:
Server:
const int listenPort = 8001;
bool done = false;
UdpClient listener = new UdpClient(listenPort);
try
{
while (!done)
{
string text_to_send = satt.Text;
if (text_to_send.Length == 0)
{
done = true;
}
else
{
byte[] send_buffer = Encoding.ASCII.GetBytes(text_to_send);
try
{
string IPAddress1 = "";
IPHostEntry Host = default(IPHostEntry);
string Hostname = null;
Hostname = System.Environment.MachineName;
Host = Dns.GetHostEntry(Hostname);
foreach (IPAddress IP in Host.AddressList)
{
if (IP.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
IPAddress1 = Convert.ToString(IP);
}
else
{
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
string data_recieved;
byte[] recieve_byte_array;
try
{
while (!done)
{
Console.WriteLine("Looking for attack buddies " + groupEP);
recieve_byte_array = listener.Receive(ref groupEP);
Console.WriteLine("New buddy found at + " + groupEP.ToString());
data_recieved = Encoding.ASCII.GetString(recieve_byte_array, 0, recieve_byte_array.Length);
Console.WriteLine(data_recieved);
}
}
catch (Exception n)
{
Console.WriteLine("Attack information could not be sent. Please make sure your buddies are reachable" + n.ToString());
}
}
}
}
catch (Exception j)
{
Console.WriteLine("Please make sure all needed information is filled out");
}
Client:
const int listenPort = 8001;
bool done = false;
UdpClient listener = new UdpClient(listenPort);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
string data_recieved;
string searchcount_sent = searchcount.ToString();
byte[] send_byte_array;
byte[] recieve_byte_array;
try
{
while (!done)
{
string IPAddress1 = "";
IPHostEntry Host = default(IPHostEntry);
string Hostname = null;
Hostname = System.Environment.MachineName;
Host = Dns.GetHostEntry(Hostname);
foreach (IPAddress IP in Host.AddressList)
{
if (IP.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
IPAddress1 = Convert.ToString(IP);
}
}
string text_to_send = "Request to connect from: " + IPAddress1;
if (text_to_send.Length == 0)
{
done = true;
}
else
{
MessageBox.Show("Now listening on port 8001.");
Socket sending_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPAddress send_to_address = IPAddress.Parse(RecieveIP.Text);
IPEndPoint sending_end_point = new IPEndPoint(send_to_address, 8001);
Console.WriteLine("Now sending out packet to be acknolwedged by lead computer.");
byte[] send_buffer = Encoding.ASCII.GetBytes(text_to_send);
Console.WriteLine("Listening for the attack information on port " + listenPort);
recieve_byte_array = listener.Receive(ref groupEP);
data_recieved = Encoding.ASCII.GetString(recieve_byte_array, 0, recieve_byte_array.Length);
try
{
sending_socket.SendTo(send_buffer, sending_end_point);
}
catch (Exception send_exception)
{
Console.WriteLine("Exception {0}", send_exception);
}
MessageBox.Show("Listening for attack information.");
The two computers are finding each other via arp-a. So wondering why they would not be receiving each others message? Thanks.

Related

How to Send/Receive data over network in socket program in c#

I am working on a program which has two parts Listner (Server) and Sender (Client). Following is my code
Server
static void Main(string[] args)
{
byte[] buffer = new byte[1000];
byte[] msg = Encoding.ASCII.GetBytes("From server\n");
string data = null;
IPHostEntry iphostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = iphostInfo.AddressList[0];
IPEndPoint localEndpoint = new IPEndPoint(ipAddress, 32000);
ConsoleKeyInfo key;
int count = 0;
Socket sock = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
sock.Bind(localEndpoint);
sock.Listen(5);
while (true)
{
Console.WriteLine("\nWaiting for clients..{0}", count);
Socket confd = sock.Accept();
int b = confd.Receive(buffer);
data += Encoding.ASCII.GetString(buffer, 0, b);
Console.WriteLine("" + data);
data = null;
confd.Send(msg);
Console.WriteLine("\n<< Continue 'y' , Exit 'e'>>");
key = Console.ReadKey();
if (key.KeyChar == 'e')
{
Console.WriteLine("\nExiting..Handled {0} clients", count);
confd.Close();
System.Threading.Thread.Sleep(5000);
break;
}
confd.Close();
count++;
}
}
Client
static void Main(string[] args)
{
byte[] data = new byte[10];
IPHostEntry iphostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAdress = iphostInfo.AddressList[0];
IPEndPoint ipEndpoint = new IPEndPoint(ipAdress, 32000);
Socket client = new Socket(ipAdress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try
{
client.Connect(ipEndpoint);
Console.WriteLine("Socket created to {0}", client.RemoteEndPoint.ToString());
byte[] sendmsg = Encoding.ASCII.GetBytes("Hello My Name Is Shaiwal Tripathi\n");
int n = client.Send(sendmsg);
int m = client.Receive(data);
Console.WriteLine("" + Encoding.ASCII.GetString(data));
client.Shutdown(SocketShutdown.Both);
client.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("Transmission end.");
Console.ReadKey();
}
It's working fine on single computer. But when I am trying to run it on LAN network by assigning the IP Address manually, I'm getting the following error.
The requested address is not valid in its context
This is how I'm assigning the IP Address.
IPAddress ipAdress = IPAddress.Parse("168.168.0.8");
IPEndPoint ipEndpoint = new IPEndPoint(ipAdress, 32000);
Socket client = new Socket(ipAdress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
client.Bind(ipEndpoint);
client.Connect(ipEndpoint);
My goal is to send data to a target computer on network and target computer should receive the incoming data.

Sending asynchronous message from server to client

I am writing program to solve the dining philosophers problem without a server. It should work by message passing. My application should run 5 times and then connect to each other and solve the problem by themselves. I put a server side and client side in each app, and I gave them a port number. This image will show what i am talking about:
https://www.photobox.co.uk/my/photo/full?photo_id=500223105218
All I want is sending messages between client sides and server sides.
But I have an error in sending message asynchronously from server side by socket handler.(mentioned it below)
I searched about that but could not find any code similar, so how can I send messages directly from server side to client side?
And, how is my idea? is that right? or it is wrong.
This is part of my code which works well:
String status = "Thinking";
Boolean right = false;
Boolean left = false;
// Receiving byte array
byte[] bytes = new byte[1024];
SocketPermission permission;
Socket sListener;
Socket sListener1;
Socket sListener2;
Socket sListener3;
Socket sListener4;
Socket handler1;
Socket handler2;
Socket handler3;
Socket handler4;
Socket handler5;
Socket senderSock;
Socket senderSock1;
Socket senderSock2;
Socket senderSock3;
Socket senderSock4;
public Form1()
{
InitializeComponent();
}
//start button
private void button1_Click(object sender, EventArgs e)
{
try
{
IPEndPoint ipEndPoint=null;
IPEndPoint ipEndPoint1=null;
IPEndPoint ipEndPoint2 = null;
IPEndPoint ipEndPoint3 = null;
IPEndPoint ipEndPoint4 = null;
// Creates one SocketPermission object for access restrictions
permission = new SocketPermission(
NetworkAccess.Accept, // Allowed to accept connections
TransportType.Tcp, // Defines transport types
"", // The IP addresses of local host
SocketPermission.AllPorts // Specifies all ports
);
// Listening Socket object
sListener = null;
sListener1 = null;
sListener2 = null;
sListener3 = null;
sListener4 = null;
// Ensures the code to have permission to access a Socket
permission.Demand();
// Resolves a host name to an IPHostEntry instance
IPHostEntry ipHost = Dns.GetHostEntry("");
// Gets first IP address associated with a localhost
IPAddress ipAddr = ipHost.AddressList[0];
// Creates a network endpoint
if (Sport.Text == "1000")
{
ipEndPoint = new IPEndPoint(ipAddr, Convert.ToInt32(Sport.Text));
}else if (Sport.Text == "1001")
{
ipEndPoint1 = new IPEndPoint(ipAddr, Convert.ToInt32(Sport.Text));
}
else if (Sport.Text == "1002")
{
ipEndPoint2 = new IPEndPoint(ipAddr, Convert.ToInt32(Sport.Text));
}
else if (Sport.Text == "1003")
{
ipEndPoint3 = new IPEndPoint(ipAddr, Convert.ToInt32(Sport.Text));
}
else if (Sport.Text == "1004")
{
ipEndPoint4 = new IPEndPoint(ipAddr, Convert.ToInt32(Sport.Text));
}
// Associates a Socket with a local endpoint
if (Sport.Text == "1000")
{
// Create one Socket object to listen the incoming connection
sListener = new Socket(
ipAddr.AddressFamily,
SocketType.Stream,
ProtocolType.Tcp
);
sListener.Bind(ipEndPoint);
sListener.Listen(10);
}else if(Sport.Text == "1001")
{
sListener1 = new Socket(
ipAddr.AddressFamily,
SocketType.Stream,
ProtocolType.Tcp
);
sListener1.Bind(ipEndPoint1);
sListener1.Listen(10);
}
else if (Sport.Text == "1002")
{
sListener2 = new Socket(
ipAddr.AddressFamily,
SocketType.Stream,
ProtocolType.Tcp
);
sListener2.Bind(ipEndPoint2);
sListener2.Listen(10);
}
else if (Sport.Text == "1003")
{
sListener3 = new Socket(
ipAddr.AddressFamily,
SocketType.Stream,
ProtocolType.Tcp
);
sListener3.Bind(ipEndPoint3);
sListener3.Listen(10);
}
else if (Sport.Text == "1004")
{
sListener4 = new Socket(
ipAddr.AddressFamily,
SocketType.Stream,
ProtocolType.Tcp
);
sListener4.Bind(ipEndPoint4);
sListener4.Listen(10);
}
label3.Text = "Server started.";
statusLabel.Text = "READY";
button1.Enabled = false;
}
catch (Exception exc) { MessageBox.Show(exc.ToString()); }
}
//connect button
private void button2_Click(object sender, EventArgs e)
{
try
{
IPEndPoint ipEndPoint = null;
IPEndPoint ipEndPoint1 = null;
IPEndPoint ipEndPoint2 = null;
IPEndPoint ipEndPoint3 = null;
IPEndPoint ipEndPoint4 = null;
// Create one SocketPermission for socket access restrictions
SocketPermission permission = new SocketPermission(
NetworkAccess.Connect, // Connection permission
TransportType.Tcp, // Defines transport types
"", // Gets the IP addresses
SocketPermission.AllPorts // All ports
);
// Ensures the code to have permission to access a Socket
permission.Demand();
// Resolves a host name to an IPHostEntry instance
IPHostEntry ipHost = Dns.GetHostEntry("");
// Gets first IP address associated with a localhost
IPAddress ipAddr = ipHost.AddressList[0];
// Creates a network endpoint
if (Cport.Text == "1000")
{
ipEndPoint = new IPEndPoint(ipAddr, Convert.ToInt32(Cport.Text));
}else if (Cport.Text == "1001")
{
ipEndPoint1 = new IPEndPoint(ipAddr, Convert.ToInt32(Cport.Text));
}
else if (Cport.Text == "1002")
{
ipEndPoint2 = new IPEndPoint(ipAddr, Convert.ToInt32(Cport.Text));
}
else if (Cport.Text == "1003")
{
ipEndPoint3 = new IPEndPoint(ipAddr, Convert.ToInt32(Cport.Text));
}
else if (Cport.Text == "1004")
{
ipEndPoint4 = new IPEndPoint(ipAddr, Convert.ToInt32(Cport.Text));
}
if (Cport.Text == "1000")//A
{
// Create one Socket object to setup Tcp connection
senderSock = new Socket(
ipAddr.AddressFamily,// Specifies the addressing scheme
SocketType.Stream, // The type of socket
ProtocolType.Tcp // Specifies the protocols
);
senderSock.NoDelay = false; // Using the Nagle algorithm
// Establishes a connection to a remote host
senderSock.Connect(ipEndPoint);
statusLabel.Text = "Socket connected to " + senderSock.RemoteEndPoint.ToString();
}
else if (Cport.Text == "1001")//B
{
senderSock1 = new Socket(
ipAddr.AddressFamily,
SocketType.Stream,
ProtocolType.Tcp
);
senderSock1.NoDelay = false;
senderSock1.Connect(ipEndPoint1);
statusLabel.Text = "Socket connected to " + senderSock1.RemoteEndPoint.ToString();
}
else if (Cport.Text == "1002")//C
{
senderSock2 = new Socket(
ipAddr.AddressFamily,
SocketType.Stream,
ProtocolType.Tcp
);
senderSock2.NoDelay = false;
senderSock2.Connect(ipEndPoint2);
statusLabel.Text = "Socket connected to " + senderSock2.RemoteEndPoint.ToString();
}
else if (Cport.Text == "1003")//D
{
senderSock3 = new Socket(
ipAddr.AddressFamily,
SocketType.Stream,
ProtocolType.Tcp
);
senderSock3.NoDelay = false;
senderSock3.Connect(ipEndPoint3);
statusLabel.Text = "Socket connected to " + senderSock3.RemoteEndPoint.ToString();
}
else if (Cport.Text == "1004")//E
{
senderSock4 = new Socket(
ipAddr.AddressFamily,
SocketType.Stream,
ProtocolType.Tcp
);
senderSock4.NoDelay = false;
senderSock4.Connect(ipEndPoint4);
statusLabel.Text = "Socket connected to " + senderSock4.RemoteEndPoint.ToString();
}
button2.Enabled = false;
}
catch (Exception exc) { MessageBox.Show(exc.ToString()); }
label3.Text = "wait...";
Thread.Sleep(4000);
send_st();
}
And here is my code where I get an Error in "Send(handler1, status);"
The error is: "Object reference not set to an instance of an object"
//send status from clnt to server
public void sendCToS(String str)
{
try
{
// Sending message
//<Client Quit> is the sign for end of data
byte[] msg = Encoding.Unicode.GetBytes(str + "<Client Quit>");
// Sends data to a connected Socket.
//send status from client to server
int bytesSend = senderSock.Send(msg);//receiver server tasmim giri va response send mikone
}
catch (Exception exc) { MessageBox.Show(exc.ToString()); }
}
//it send hungry status from both to both!
public void send_st()
{
// Resolves a host name to an IPHostEntry instance
IPHostEntry ipHost = Dns.GetHostEntry("");
// Gets first IP address associated with a localhost
IPAddress ipAddr = ipHost.AddressList[0];
Random rnd = new Random();
int delay = rnd.Next(2000, 5000);
while (true)
{
//System.Threading.Thread.Sleep(2000);
statusLabel.Text = status;
statusLabel.ForeColor = System.Drawing.Color.Blue;
Thread.Sleep(delay);
if (Sport.Text == "1000")//A
{
status = "hungry";
statusLabel.Text = "HUNGRY";
statusLabel.ForeColor = System.Drawing.Color.Red;
//send status from server to clint
Send(handler1, status);
//send status from clnt to server
sendCToS(status);
label3.Text = "status Sent to left and right";
}
else if (Sport.Text == "1001")//B
{
Thread.Sleep(2000);
status = "hungry";
statusLabel.Text = "HUNGRY";
statusLabel.ForeColor = System.Drawing.Color.Red;
//send status from server to clint
Send(handler2, status);
//send status from clnt to server
sendCToS(status);
label3.Text = "status Sent to left and right";
}
else if (Sport.Text == "1002")//C
{
status = "hungry";
statusLabel.Text = "HUNGRY";
statusLabel.ForeColor = System.Drawing.Color.Red;
//send status from server to clint
Send(handler3, status);
//send status from clnt to server
sendCToS(status);
label3.Text = "status Sent to left and right";
}
else if (Sport.Text == "1003")//D
{
Thread.Sleep(2000);
status = "hungry";
statusLabel.Text = "HUNGRY";
statusLabel.ForeColor = System.Drawing.Color.Red;
//send status from server to clint
Send(handler4, status);
//send status from clnt to server
sendCToS(status);
label3.Text = "status Sent to left and right";
}
else if (Sport.Text == "1004")//E
{
Thread.Sleep(3000);
status = "hungry";
statusLabel.Text = "HUNGRY";
statusLabel.ForeColor = System.Drawing.Color.Red;
//send status from server to clint
Send(handler5, status);
//send status from clnt to server
sendCToS(status);
label3.Text = "status Sent to left and right";
}
}
}
//server side
// Thread signal.
public static ManualResetEvent allDone = new ManualResetEvent(false);
public void AcceptCallback(IAsyncResult ar)
{
Socket listener = null;
// A new Socket to handle remote host communication
Socket handler = null;
try
{
// Receiving byte array
byte[] buffer = new byte[1024];
// Get Listening Socket object
listener = (Socket)ar.AsyncState;
// Create a new socket
handler = listener.EndAccept(ar);
// Using the Nagle algorithm
handler.NoDelay = false;
StateObject state = new StateObject();
// Begins to asynchronously receive data
handler.BeginReceive(
buffer, // An array of type Byt for received data
0, // The zero-based position in the buffer
buffer.Length, // The number of bytes to receive
0,// Specifies send and receive behaviors
new AsyncCallback(ReceiveCallback),//An AsyncCallback delegate
state // Specifies infomation for receive operation
);
}
catch (Exception exc) { MessageBox.Show(exc.ToString()); }
}
public void ReceiveCallback(IAsyncResult ar)
{
String response = "ok";
try
{
// Retrieve the state object and the handler socket
// from the asynchronous state object.
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
// Read data from the client socket.
int bytesRead = handler.EndReceive(ar);
// Received message
string content = string.Empty;
if (bytesRead > 0)
{
// There might be more data, so store the data received so far.
state.sb.Append(Encoding.ASCII.GetString(
state.buffer, 0, bytesRead));
// Check for end-of-file tag. If it is not there, read
// more data.
content = state.sb.ToString();
if (content.IndexOf("<Client Quit>") > -1)
{
// All the data has been read from the client
label3.Text = content;
}
else {
// Not all data received. Get more.
handler.BeginReceive(state.buffer, 0,StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
And this is the rest of the server side functions:
//func for echo back to client
private void Send(Socket handler, String data)
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data);
// Begin sending the data to the remote device.
handler.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), handler);
}
public void SendCallback(IAsyncResult ar)
{
try
{
// A Socket which has sent the data to remote host
Socket handler = (Socket)ar.AsyncState;
// The number of bytes sent to the Socket
int bytesSend = handler.EndSend(ar);
label3.Text = "Sent {0} bytes to Client" + bytesSend;
}
catch (Exception exc) { MessageBox.Show(exc.ToString()); }
I belive the problem is with this line:
senderSock.Send(msg);
You never instantiated the senderSock, you only declared it.
try this:
senderSock= new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
senderSock.Send(msg);

Server/Client Socket connection

I am trying to send data from client to server over socket connection. I succesfully sent first data but when i try to send second one it never sends and when i try to send third one it gives me Sockets.SocketException How can I solve that?
Server
byte[] buffer = new byte[1000];
IPHostEntry iphostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = iphostInfo.AddressList[0];
IPEndPoint localEndpoint = new IPEndPoint(ipAddress, 8080);
Socket sock = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
sock.Bind(localEndpoint);
sock.Listen(5);
while (true) {
Socket confd = sock.Accept();
string data = null;
int b = confd.Receive(buffer);
data += Encoding.ASCII.GetString(buffer, 0, b);
Console.WriteLine("" + data);
confd.Close();
}
Client
byte[] data = new byte[10];
IPHostEntry iphostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAdress = iphostInfo.AddressList[0];
IPEndPoint ipEndpoint = new IPEndPoint(ipAdress, 8080);
Socket client = new Socket(ipAdress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try {
client.Connect(ipEndpoint);
Console.WriteLine("Socket created to {0}", client.RemoteEndPoint.ToString());
while (true) {
string message = Console.ReadLine();
byte [] sendmsg = Encoding.ASCII.GetBytes(message);
int n = client.Send(sendmsg);
}
}
catch (Exception e) {
Console.WriteLine(e.ToString());
}
Console.WriteLine("Transmission end.");
Console.ReadKey();
Okay, what a silly mistake. Here is the solution, we should accept socket once.
while (true) {
Socket confd = sock.Accept();
string data = null;
int b = confd.Receive(buffer);
data += Encoding.ASCII.GetString(buffer, 0, b);
Console.WriteLine("" + data);
confd.Close();
}
Changed to
Socket confd = sock.Accept();
while (true) {
//Socket confd = sock.Accept();
string data = null;
int b = confd.Receive(buffer);
data += Encoding.ASCII.GetString(buffer, 0, b);
Console.WriteLine("" + data);
//confd.Close();
}
If there any documentation about sockets, comment it please. I would like to read.

C# TCP Chat-Server: Connection only works one way

I've got a generic TCP Client and TCP Listener setup on my main laptop and my other laptop. The client and listener are their own separate programs, so I've had a client and server running on both laptops to try and get a simple instant messenger going.
The client and server will happily communicate with each other if both programs are executed on the same laptop. This is true for both my main and other laptop.
My main laptop's client will happily send messages to my other laptop, and the other laptop will gracefully receive messages from my main laptop.
However, when my other laptop's client sends a message to my main laptop's server it gets a timeout-related, communication-failed type of error. It just doesn't send the message.
Error message (caught by try-catch); "A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond {my IP:port number}."
I'm getting the IP and port numbers correct, so rule that out.
There's no firewall business because the other laptop doesn't care at all about receiving messages from my main laptop.
I've also tried random port numbers and made sure that the client on my main laptop is connecting over the same port number that my other laptop's sever is listening on (or accepting messages from).
So why isn't my other laptop successfully sending messages to my main laptop?
The client asks for the user to enter an IP and then a port number. It then waits for the user to enter a message, then connects and sends that message to the IP via the given port number.
The server asks the user to enter a port number and prints messages received through that port.
Here's the code for the client program;
static void Main(string[] args)
{
string IP = localIPAddress();
Console.WriteLine("Your IP: " + IP); //provides IP number
Console.Write("Enter IP to connect to: ");
string connectToIP = Console.ReadLine();
if (connectToIP == "self")
{
connectToIP = localIPAddress();
// if I want to test both on the same computer
}
Console.WriteLine("\nEnter port number: ");
int portNo = int.Parse(Console.ReadLine());
while (true)
{
string message = Console.ReadLine();
try
{
// connection doesn't begin until ReadLine is done
request(connectToIP, portNo, message);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
public static string localIPAddress()
{
IPHostEntry host;
string localIP = "?";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
localIP = ip.ToString();
}
}
return localIP;
}
static void request(string address, int port, string message)
{
TcpClient client = new TcpClient();
client.SendTimeout = 1000;
client.ReceiveTimeout = 1000;
try
{
client.Connect(address, port);
StreamWriter sw = new StreamWriter(client.GetStream());
sw.WriteLine(message);
sw.Flush();
sw.Close();
}
catch (Exception a)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(a.Message.ToString());
Console.ResetColor();
}
}
Here's the code for the server;
static void Main(string[] args)
{
Console.WriteLine("Your IP: " + localIPAddress());
Console.Write("Enter port number you're receiving from: ");
int portNo = int.Parse(Console.ReadLine());
TcpListener listener = new TcpListener(IPAddress.Any, portNo);
Socket connection;
NetworkStream socketStream;
listener.Start();
while (true)
{
connection = listener.AcceptSocket();
connection.SendTimeout = 1000;
connection.ReceiveTimeout = 1000;
socketStream = new NetworkStream(connection);
try
{
respond(socketStream);
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
socketStream.Close();
connection.Close();
}
}
}
public static string localIPAddress()
{
IPHostEntry host;
string localIP = "?";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
localIP = ip.ToString();
}
}
return localIP;
}
static void respond(NetworkStream strm)
{
List<string> sentIn = new List<string>();
StreamReader sr = new StreamReader(strm);
while (sr.Peek() != -1)
sentIn.Add(sr.ReadLine());
sr.Close();
foreach (string s in sentIn)
{
Console.WriteLine(s);
}
}
Is there a problem with my code? There have been no Firewall-related messages when either laptop uses these programs.
It might be the sw.Flush() for the client, because that used to cause the sending process to freeze.
Thanks in advance. Once I get this problem sorted, I can start wondering how this can be used to make a multiplayer XNA game.
You might want to try making the timeouts a little longer (or remove them all together; they caused problems for me). Also, it's really a good idea to create a thread to receive messages while you handle the sending on the main thread.
Some notes:
You can use "loopback" or "127.0.0.1" if you'd like to connect to your local IP
if (connectToIP == "self")
{
connectToIP = localIPAddress();
// if I want to test both on the same computer
}
You really shouldn't connect, send a single message, and then disconnect, only to connect again.
Try something like this for the client:
using System.Threading;
static void Main(string[] args)
{
TcpClient client = new TcpClient();
Console.Write("IP: ");
string ip = Console.ReadLine();
Console.Write("Port: ");
int port = int.Parse(Console.ReadLine());
try
{
client.Connect(ip, port);
StreamWriter sw = new StreamWriter(client.GetStream());
sw.AutoFlush = true;
StreamReader sr = new StreamReader(client.GetStream());
Thread readThread = new Thread(() => readSocket(sr));
readThread.Start(); //Run readSocket() at the same time
string message = "";
while (message != "exit")
{
message = Console.ReadLine();
sw.WriteLine(message);
}
client.Close();
return;
}
catch (Exception e) { Console.WriteLine(e.ToString()); }
}
static void readSocket(StreamReader sr)
{
try
{
string message = "";
while ((message = sr.ReadLine()) != null)
{
Console.WriteLine(message);
}
}
catch (System.IO.IOException) { /*when we force close, this goes off, so ignore it*/ }
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
Here's an example of the Server:
static void Main(string[] args)
{
Console.Write("Port: ");
int port = int.Parse(Console.ReadLine());
TcpListener server = new TcpListener(IPAddress.Any, port);
try
{
server.Start();
TcpClient client = server.AcceptTcpClient();
StreamWriter sw = new StreamWriter(client.GetStream());
sw.AutoFlush = true;
StreamReader sr = new StreamReader(client.GetStream());
Thread readThread = new Thread(() => readSocket(sr));
readThread.Start();
string message = "";
while (message != "exit")
{
message = Console.ReadLine();
sw.WriteLine(message);
}
client.Close();
return;
}
catch (Exception e) { Console.WriteLine(e.ToString()); }
}
static void readSocket(StreamReader sr)
{
try
{
string message = "";
while ((message = sr.ReadLine()) != null)
{
Console.WriteLine(message);
}
}
catch (System.IO.IOException) { /*when we force close, this goes off, so ignore it*/ }
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
Here is the code for an Async server that forwards messages to all connected clients (If you were worried about not being able to share a port).
I'm trying to keep these examples simple, but it's probably a good idea to add more exception handling to all of them.
class Server
{
private int port;
private Socket serverSocket;
private List<StateObject> clientList;
private const int DEFAULT_PORT = 1338;
public Server()
{
this.port = 1338; //default port
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientList = new List<StateObject>();
}
public Server(int port)
{
this.port = port;
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientList = new List<StateObject>();
}
public void startListening(int port = DEFAULT_PORT)
{
this.port = port;
serverSocket.Bind(new IPEndPoint(IPAddress.Any, this.port));
serverSocket.Listen(1);
serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
}
private void AcceptCallback(IAsyncResult AR)
{
try
{
StateObject state = new StateObject();
state.workSocket = serverSocket.EndAccept(AR);
//Console.WriteLine("Client Connected");
clientList.Add(state);
state.workSocket.BeginReceive(state.buffer, 0, StateObject.BufferSize, SocketFlags.None, new AsyncCallback(ReceiveCallback), state);
serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
}
catch { }
}
private void ReceiveCallback(IAsyncResult AR)
{
StateObject state = (StateObject)AR.AsyncState;
Socket s = state.workSocket;
try
{
int received = s.EndReceive(AR);
if (received == 0)
return;
if (received > 0)
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, received));
string content = state.sb.ToString();
if (content.IndexOf(Environment.NewLine) > -1)
{
//Console.WriteLine(content);
foreach (StateObject others in clientList)
if (others != state)
others.workSocket.Send(Encoding.ASCII.GetBytes(content.ToCharArray()));
state.sb.Clear();
}
Array.Clear(state.buffer, 0, StateObject.BufferSize);
s.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
}
catch (Exception huh) {
s.Close();
s.Dispose();
//Console.WriteLine("Client Disconnected");
clientList.Remove(state);
return;
}
}
class StateObject
{
public Socket workSocket = null;
public const int BufferSize = 1024;
public byte[] buffer = new byte[BufferSize];
public StringBuilder sb = new StringBuilder();
}
}

c# being done with a remote computer sending and receiving data using stunserver

I can not send data stunserver remote computer using the two. Data comes from local computers, but data on remote computers is not going to come.
I'm using my program, stunserver
public void run()
{
UpdateText("Now Listening..");
remoteSender = new IPEndPoint(IPAddress.Any, 0);
tempRemoteEP = (EndPoint)remoteSender;
byte[] packet = new byte[1024];
while (true)
{
if (socket.Available > 0)
{
this.nbBytesRx = socket.ReceiveFrom(packet, ref tempRemoteEP);
nbPackets++;
seqNo = BitConverter.ToInt16(packet, 0);
UpdateText(nbPackets.ToString() + ":" + seqNo.ToString() + " / ");
}
}
}
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.Bind(new IPEndPoint(IPAddress.Any, 0));
string localEP = socket.LocalEndPoint.ToString();
string publicEP = "";
string netType = "";
STUN_Result result = STUN_Client.Query("stunserver.org", 3478, socket);
netType = result.NetType.ToString();
if (result.NetType != STUN_NetType.UdpBlocked)
{
publicEP = result.PublicEndPoint.ToString();
}
else
{
publicEP = "";
}
UpdateText("Local EP:" + localEP);
UpdateText("Public EP:" + publicEP);
ThreadStart startMethod = new ThreadStart(this.run);
thread = new Thread(startMethod);
thread.Start();
I am working on the same problem, and using the same library.
Did you check if you get your endpoint? I found our that pointed server wasn`t online. So I made a List of servers to go throught.
My method to get public EP:
public static IPEndPoint GetMyPublicEP() {
// Create new socket for STUN client.
Socket _socket = new Socket
(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
_socket.Bind(new IPEndPoint(IPAddress.Any, 0));
List<string> _stunServers = new List<string> { // список стан серверов для проверки своей ендпоинт, не все работают
"stun.l.google.com:19302",
"stun1.l.google.com:19302",
"stun2.l.google.com:19302",
"stun3.l.google.com:19302",
"stun4.l.google.com:19302",
"stun01.sipphone.com",
"stun.ekiga.net",
"stun.fwdnet.net",
"stun.ideasip.com",
"stun.iptel.org",
"stun.rixtelecom.se",
"stun.schlund.de",
"stunserver.org",
"stun.softjoys.com",
"stun.voiparound.com",
"stun.voipbuster.com",
"stun.voipstunt.com",
"stun.voxgratia.org",
"stun.xten.com"
};
foreach (string server in _stunServers)
{
try
{
STUN_Result result = STUN_Client.Query(server, 3478, _socket);
IPEndPoint myPublicEPStun = result.PublicEndPoint;
if (myPublicEPStun != null)
{
_myPublicEPStun = myPublicEPStun;
break;
}
}
catch (Exception E)
{
Console.WriteLine("Якась необ`ясніма магія трапилась");
}
}
return _myPublicEPStun;
}
I had the same problem... i solved it disabling Windows Firewall. It was blocking all the traffic.

Categories

Resources