Socket communication C# - c#

I am using this class to send an Echo test from/to my application
public class SocketClient
{
Socket socket = null;
static ManualResetEvent clientDone = new ManualResetEvent(false);
const int TIMEOUT_MILLISECONDS = 5000;
const int MAX_BUFFER_SIZE = 2048;
public SocketClient()
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
}
public string Send(string serverName, int portNumber, string data)
{
string response = "Timeout";
if (socket != null)
{
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.RemoteEndPoint = new DnsEndPoint(serverName, portNumber);
socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
{
response = e.SocketError.ToString();
clientDone.Set();
});
byte[] payload = Encoding.UTF8.GetBytes(data);
socketEventArg.SetBuffer(payload, 0, payload.Length);
clientDone.Reset();
socket.SendToAsync(socketEventArg);
clientDone.WaitOne(TIMEOUT_MILLISECONDS);
}
else
{
response = "not initialized";
}
return response;
}
public string Recieve(int portNumber)
{
string response = "Timeout";
if (socket != null)
{
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.SetBuffer(new Byte[MAX_BUFFER_SIZE], 0, MAX_BUFFER_SIZE);
socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
{
if (e.SocketError == SocketError.Success)
{
response = Encoding.UTF8.GetString(e.Buffer, e.Offset, e.BytesTransferred);
response.Trim('\0');
}
else
{
response = e.SocketError.ToString();
}
clientDone.Set();
});
socketEventArg.RemoteEndPoint = new IPEndPoint(IPAddress.Any, portNumber);
clientDone.Reset();
socket.ReceiveFromAsync(socketEventArg);
clientDone.WaitOne(TIMEOUT_MILLISECONDS);
}
return response;
}
public void Close()
{
socket.Close();
}
}
and here's how I use it:
SocketClient client = new SocketClient();
client.Send("192.168.1.2",77 , "besm ellah");
textBox1.Text=client.Recieve(77);
It always through Argument Exception was unhandled at socket.SendToAsync(socketEventArg);
"The parameter remoteEP must not be of type DnsEndPoint."
"Parameter name: remoteEP"
I enabled the feature of simple TCP/IP on windows features, but it also doesn't work.
-UPDATE-
I tried changing the code to be:
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
socketEventArg.RemoteEndPoint = new IPEndPoint(localIPs[3], portNumber);
it doesn't give an exception, but the message doesn't get through.

Well, it looks like you should change it to be a different type of endpoint, rather than DNS endpoint.
I think you should be using an IPEndPoint
http://msdn.microsoft.com/en-us/library/system.net.sockets.socketasynceventargs.aspx

Related

Send and receive data in c# network programming winform

I have a small server that is received and sends the message back to the client.
this is the client-side
when I open the client it will connect to server through Connect()
public Form1()
{
InitializeComponent();
Connect();
CheckForIllegalCrossThreadCalls = false;
}
this is my connect
void Connect()
{
ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9999);
server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
server.Connect(ipep);
}
catch (SocketException e)
{
MessageBox.Show(Convert.ToString(e));
}
Thread listen = new Thread(Receive);
listen.IsBackground = true; ;
listen.Start();
}
and I have a receive like this
void Receive()
{
datarec = new byte[1024];
try
{
while (true)
{
string StringData;
rec = server.Receive(datarec);
StringData = Encoding.ASCII.GetString(data, 0, rec);
txtShow.Text = StringData;
}
}
catch
{
Close();
}
}
and I send data through a button have Send method
void Send(string s)
{
data = new byte[1024];
data = Encoding.ASCII.GetBytes(s);
server.Send(data, data.Length, SocketFlags.None);
}
Send button
private void button1_Click(object sender, EventArgs e)
{
string s = txtText.Text;
Send(s);
}
this is the server-side
I have a thread server
public static void Process(Socket client)
{
byte[] data = new byte[1024];
int recv;
string dataInput;
IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;
Console.WriteLine("Connected with {0} at port {1}", clientep.Address, clientep.Port);
while (true)
{
try
{
recv = client.Receive(data);
dataInput = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine(dataInput);
client.Send(data);
}
catch (SocketException e)
{
Console.WriteLine(e);
}
}
}
this is the server main
public static void Main()
{
byte[] rec = new byte[1024];
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9999);
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
server.Bind(ipep);
server.Listen(10);
Console.WriteLine("Waiting for client...");
Console.WriteLine("LOG CHAT");
while (true)
{
Socket client = server.Accept();
Core core = new Core();
Thread t = new Thread(() => Core.Process(client));
t.Start();
}
}
the server receive message but when it sends a message back it has an error "An established connection was aborted by the software in your host machine"
Can you guys tell me where I was wrong and how can I fix it?
When you call client.Send(data) in your server code, you will send the whole 1024 byte buffer back to the client, not just the data received.
Encoding.ASCII.GetString in the client could fail when processing this garbage and the exception will close the connection.
Try to replace client.Send(data) by client.Send(data, recv, SocketFlags.None).
Also, you should not update UI controls directly from a background thread, Use Control.Invoke for this. Failing to do so will also throw an exception and close the connection.

Socket Programming [Socket and Server]

I am trying to make a message server and I have an error with this code:
The error "is only one use of each socket address can be normally permitted"
Server:
class Program
{
//Server Control
static bool stop = false;
static bool pause_listening = false;
//Server Info
static int port = 11000;
static string server_ip = null;
//User Declaration
static List<user> allUsers = new List<user>();
static int users = 0;
//IP Address
static IPAddress ipaddr;
static IPEndPoint localEP;
static IPEndPoint userportEP;
static IPEndPoint temp;
//Data
static string data = null;
static byte[] bytes = new Byte[1024];
//Threads
static Thread listener = new Thread(listen);
static Thread server_control = new Thread(Options);
static Thread UserPort = new Thread(addUserPort);
static void Main(string[] args)
{
Console.WriteLine("Message Server");
start();
}
static void start()
{
server_ip = input("What is your local IPv4 address");
ipaddr = IPAddress.Parse(server_ip);
allUsers.Add(new user());
allUsers[users].name = "Admin";
allUsers[users].ip = server_ip;
allUsers[users].desc = "Nimda";
allUsers[users].id = 0;
localEP = new IPEndPoint(ipaddr, port);
userportEP = new IPEndPoint(ipaddr, 1300);
UserPort.Start();
listener.Start();
server_control.Start();
}
static void addUserPort()
{
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(userportEP);
listener.Listen(10);
Console.WriteLine("User Listener Started");
// Start listening for connections.
while (pause_listening || stop != true)
{
// Program is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
string value = null;
// An incoming connection needs to be processed.
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
value += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (value.IndexOf("<!EOM>") > -1)
{
Console.WriteLine("Someone Requested");
if(value.IndexOf( "!au") > -1)
{
String[] rawData = value.Split('|');
String[] userData = new String[3];
for(int x = 0; x < rawData.Length; x++)
{
String stringbuff = rawData[x];
if(stringbuff.IndexOf("name:") > -1)
{
var tempData = stringbuff.Split(':');
userData[x] = tempData[0];
}
else if (stringbuff.IndexOf("ipaddr:") > -1)
{
var tempData = stringbuff.Split(':');
userData[x] = tempData[1];
}
else if (stringbuff.IndexOf("desc:") > -1)
{
var tempData = stringbuff.Split(':');
userData[x] = tempData[2];
}
}
addUser(userData[0], userData[1], userData[2]);
}
break;
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
static void listen()
{
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
Console.WriteLine("Message Listener Started");
try
{
listener.Bind(localEP);
listener.Listen(10);
while (pause_listening || stop != true)
{
Socket handler = listener.Accept();
data = null;
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf("<!EOM>") > -1 && data.IndexOf("<!META>") > -1)
{
textSent(data);
break;
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
static void addUser(String name, String ip, String desc)
{
users++;
allUsers.Add(new user());
userportEP = new IPEndPoint(IPAddress.Parse(ip), 1300);
allUsers[users].name = name;
allUsers[users].ip = ip;
allUsers[users].desc = desc;
allUsers[users].id = users;
byte[] msg = Encoding.ASCII.GetBytes(string.Format("!Join<!PORT>{0}<!PORT><!EOM>", port));
Socket confirm = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
confirm.Bind(userportEP);
confirm.Connect(userportEP);
confirm.Send(msg);
confirm.Shutdown(SocketShutdown.Both);
confirm.Close();
}
static String input(String inputText)
{
Console.WriteLine(inputText);
return Console.ReadLine();
}
static void Options()
{
while(stop == false)
{
Console.Write("\n Server>>");
String command = Console.ReadLine();
switch (command)
{
case "stop":
stop = true;
listener.Abort();
UserPort.Abort();
StopServer();
break;
default:
Console.WriteLine("\t The command \"{0} \" is not valid", command);
break;
}
}
}
static void StopServer()
{
Console.WriteLine("Server is stopping");
Console.Read();
}
static void textSent(String text)
{
String[] rawText = text.Split(new string[] { "<!META>" }, StringSplitOptions.None) ;
String message = rawText[0];
String[] meta = rawText[1].Split(':');
String package = meta[0] + ": " + message + "<!EOM>";
SendToAll(package);
}
static void SendToAll(String pack)
{
byte[] msg = Encoding.ASCII.GetBytes(pack);
Socket send_socket= new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
for (int x = 0; allUsers.Count < x; x++)
{
temp = new IPEndPoint(IPAddress.Parse(allUsers[x].ip), port);
send_socket.Bind(temp);
send_socket.Connect(temp);
send_socket.Send(msg);
}
send_socket.Shutdown(SocketShutdown.Both);
send_socket.Close();
}
}
Client:
class Program
{
static int port;
static string server_ip;
static string ign;
static string desc;
static string ip;
static bool connected = false;
static bool exit = false;
static IPEndPoint remoteEP;
static IPEndPoint remoteUserRequestEP;
static IPEndPoint localEP;
static IPEndPoint userRequestListen;
static Socket listen;
static Socket send;
static Thread listenThread;
static Thread sendThread;
static void Main(string[] args)
{
Console.WriteLine("Message Client");
start();
}
static void start()
{
server_ip = input("Please Enter your Server I.P.");
remoteUserRequestEP = new IPEndPoint(IPAddress.Parse(server_ip), 1300);
ip = input("Enter your local IPv4 Address");
desc = input("Enter a short description");
ign = input("Enter a name to represent yourself");
localEP = new IPEndPoint(IPAddress.Parse(ip), 11000);
userRequestListen = new IPEndPoint(IPAddress.Parse(ip), 1300);
listenThread = new Thread(listening);
sendThread = new Thread(createSend);
listenThread.Start();
sendThread.Start();
}
static String input(String inputText)
{
Console.WriteLine(inputText);
return Console.ReadLine();
}
static void listening()
{
listen = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
String data;
byte[] bytes;
try
{
listen.Bind(localEP);
listen.Listen(1);
while (exit == false)
{
Socket handler = listen.Accept();
data = null;
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf("<!EOM>") > -1 )
{
string finalMSG = data.Replace("<!EOM>", null);
Console.WriteLine(finalMSG);
break;
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
static void requestAcesss()
{
byte[] msg = new byte[1024];
msg = Encoding.ASCII.GetBytes(string.Format("!au|name:{0}|ipaddr:{1}|desc:{2}|<!EOM>", ign, ip, desc));
Socket usrRequest = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
usrRequest.Bind(userRequestListen);
usrRequest.Connect(userRequestListen);
usrRequest.Send(msg);
try {
while (connected == false)
{
Socket handler = usrRequest.Accept();
string value = null;
while (true)
{
byte[] bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
value += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (value.IndexOf("<!EOM>") > -1)
{
String[] raw = value.Split(new string[] { "<!PORT>" }, StringSplitOptions.None);
port = Int32.Parse(raw[1]);
remoteEP = new IPEndPoint(IPAddress.Parse(server_ip), port);
localEP = new IPEndPoint(IPAddress.Parse(ip), port);
Console.WriteLine(port);
connected = true;
startServices();
}
break;
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
static void createSend()
{
byte[] msg = new byte[1024];
send = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
while(exit == false)
{
string raw = Console.ReadLine();
if (raw == "exit")
{
exit = true;
listenThread.Abort();
sendThread.Abort();
stop();
break;
}
string finalmsg = string.Format( raw + "<!META>name:{0}<!META><!EOM>", ign);
send.Bind(localEP);
msg = Encoding.ASCII.GetBytes(finalmsg);
send.Send(msg);
}
send.Shutdown(SocketShutdown.Both);
send.Close();
}
static void startServices()
{
listenThread.Start();
sendThread.Start();
}
static void stop()
{
Console.WriteLine("Press any key to terminate");
Console.ReadLine();
}
}
The sockets aren't used twice nor does a thread get started twice.
Having the same error, I came looking for an answer. Finally found it myself:
An earlier instance of the process may still be running, if you didn't stop it well, e.g. using just Ctrl+C.

Acquiring client's IP using IPAddress.Any

I am currently working on a simple udp client/server system, and I stumbled upon the following: When I try to get the IP of IPEndPoint (which I fetched using IPAdress.Any)in a program using UdpClient it works and I get the following result (the top one):
But when I use a normal socket instead of a UdpClient it somehow fails to distinguish the clients/IPs (bottom one). The code for both is listed below. The reason I would like to use sockets is because using the same class for both sending and receiving (not the same instance) is convenient and makes the code far more understandable.
First
bool messageReceived = false;
bool done = false;
const int listenPort = 11000;
UdpClient listener = new UdpClient(listenPort);
IPEndPoint receiveEP = new IPEndPoint(IPAddress.Any, listenPort);
string[] adresses = new string[2];
public void ReceiveCallback(IAsyncResult ar)
{
int id = 0;
Byte[] receiveBytes = listener.EndReceive(ar, ref receiveEP);
for (int i = 0; i < adresses.Length; i++)
{
if (adresses[i] == receiveEP.Address.ToString())
{
id = i;
break;
}
else if (adresses[i] == null)
{
id = i;
adresses[i] = receiveEP.Address.ToString();
break;
}
}
byte[] a= Encoding.ASCII.GetBytes("Is anybody there?");
listener.Send(a, a.Length, receiveEP);
Console.WriteLine("Received message from {0} (client {1}):", adresses[id],id);
string receiveString = Encoding.ASCII.GetString(receiveBytes);
if (receiveString == "stop")
{
done = true;
}
Console.WriteLine("Received: {0}", receiveString);
messageReceived = true;
}
public void ReceiveMessages()
{
Console.WriteLine("listening for messages");
while(!done){
try
{
messageReceived = false;
if (!messageReceived)
{
listener.BeginReceive(new AsyncCallback(ReceiveCallback), null);
}
while (!messageReceived)
{
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
Console.WriteLine("Done receiving messages...");
for (int i = 0; i < adresses.Length; i++)
{
if (adresses[i] != null)
{
Console.WriteLine(adresses[i]);
}
}
Console.ReadLine();
listener.Close();
}'
Second
bool messageReceived = false;
bool done = false;
const int listenPort = 11000;
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint receiveEP = new IPEndPoint(IPAddress.Any, listenPort);
string[] adresses = new string[2];
byte[] buffer = new byte[1024];
public void ReceiveMessages()
{
listener.Bind(receiveEP);
Console.WriteLine("listening for messages");
while (!done)
{
try
{
messageReceived = false;
if (!messageReceived)
{
listener.BeginReceive(buffer, 0,1024,SocketFlags.None,new AsyncCallback(ReceiveCallback), null);
}
while (!messageReceived)
{
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
Console.WriteLine("Done receiving messages...");
for (int i = 0; i < adresses.Length; i++)
{
if (adresses[i] != null)
{
Console.WriteLine(adresses[i]);
}
}
Console.ReadLine();
listener.Close();
}
public void ReceiveCallback(IAsyncResult ar)
{
int id = 0;
int read = listener.EndReceive(ar);
for (int i = 0; i < adresses.Length; i++)
{
if (adresses[i] == receiveEP.Address.ToString())
{
id = i;
break;
}
else if (adresses[i] == null)
{
id = i;
adresses[i] = receiveEP.Address.ToString();
break;
}
}
Console.WriteLine("Received message from {0} (client {1}):", adresses[id], id);
string receiveString = Encoding.ASCII.GetString(buffer,0,read);
if (receiveString == "stop")
{
done = true;
}
Console.WriteLine("Received: {0}", receiveString);
messageReceived = true;
}'
I've already tried Socket.ReceiveMessageFrom() and using the packetinfo it returned but I ended up with the ip4 of the server even when I send from another machine. Could someone help me out?
Even though this was never supposed to be a Q/A type of question, I've found a way of getting it to work, which means receive() changes the groupEP to the IP of the data packet's sender by just using a Socket instead of an UdpClient (I mimicked the way an UdpClient works). At the moment, it's still synchronous (listener.Receive() is a blocking call) but that will be changed in the near future:
private const int listenPort = 11000;
public static int Main()
{
bool done = false;
Listener listener = new Listener(listenPort);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
byte[] buffer = new byte[2048];
string received_data;
try
{
while (!done)
{
Console.WriteLine("Waiting for broadcast");
buffer=listener.Receive(ref groupEP);
received_data = Encoding.ASCII.GetString(buffer);
Console.WriteLine("Received a broadcast from {0}: {1}", groupEP.ToString(), received_data);
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
return 0;
}
}
public class Listener
{
public Socket client;
public AddressFamily adressFamily;
byte[] byte_buffer = new byte[2048];
public int port;
public Listener(int p)
{
port=p;
adressFamily = AddressFamily.InterNetwork;
IPEndPoint localEP;
localEP = new IPEndPoint(IPAddress.Any, port);
client = new Socket(this.adressFamily, SocketType.Dgram, ProtocolType.Udp);
client.Bind(localEP);
}
public byte[] Receive(ref IPEndPoint remoteEP)
{
IPEndPoint ipEndPoint=new IPEndPoint(IPAddress.Any,port);
EndPoint endPoint = (EndPoint)ipEndPoint;
int num = client.ReceiveFrom(byte_buffer, 2048, SocketFlags.None, ref endPoint);
remoteEP = (IPEndPoint)endPoint;
if (num < 2048)
{
byte[] array = new byte[num];
Buffer.BlockCopy(byte_buffer, 0, array, 0, num);
return array;
}
return byte_buffer;
}

Socket Programming: Server/Clients and Thread Usage

static void Main(string[] args)
{
Console.Title = "Socket Server";
Console.WriteLine("Listening for client messages");
Socket serverSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
IPAddress serverIp = IPAddress.Any;
IPEndPoint serverEP = new IPEndPoint(serverIp, 8000);
SocketPermission socketPermission = new SocketPermission(NetworkAccess.Accept,
TransportType.Tcp,
"127.0.0.1", 8000);
serverSocket.Bind(serverEP);
serverSocket.Listen(2);
while(true)
{
//Socket connection = serverSocket.Accept();
connection = serverSocket.Accept();
Thread clientThread = new Thread(new ParameterizedThreadStart(MultiUser));
clientThread.Start(connection);
}
}
public static void MultiUser(object connection)
{
byte[] serverBuffer = new byte[10025];
string message = string.Empty;
int bytes = ((Socket)connection).Receive(serverBuffer, serverBuffer.Length, 0);
message += Encoding.ASCII.GetString(serverBuffer, 0, bytes);
Console.WriteLine(message);
TcpClient client = new TcpClient();
client.Client = ((Socket)connection);
IntPtr handle = client.Client.Handle;
}
I want to write a chat program which has one server and 2 clients. The problem is that, I can not direct the message sent from the client1 to client2 via the server. How can the server distinguish threads so that it can send the received message from client1 to client2?
Each client has their own handle. You can access this via the Handle property. For example:
TcpClient client = tcpListener.AcceptTcpClient();
IntPtr handle = client.Client.Handle; //returns a handle to the connection
Then all you need to do is store this in a hashtable, and iterate through it, looking for available data. When you detect data on the wire for one of the connections, then save it and retransmit it to the other clients in the table.
Remember to make sure that you make this multithreaded so a listen request on one client does not block any send or receive functions on other clients!
I've added some code here you should be able to work with (tested it out on my system)
private void HandleClients(object newClient)
{
//check to see if we are adding a new client, or just iterating through existing clients
if (newClient != null)
{
TcpClient newTcpClient = (TcpClient)newClient;
//add this client to our list
clientList.Add(newTcpClient.Client.Handle, newTcpClient);
Console.WriteLine("Adding handle: " + newTcpClient.Client.Handle); //for debugging
}
//iterate through existing clients to see if there is any data on the wire
foreach (TcpClient tc in clientList.Values)
{
if (tc.Available > 0)
{
int dataSize = tc.Available;
Console.WriteLine("Received data from: " + tc.Client.Handle); //for debugging
string text = GetNetworkString(tc.GetStream());
//and transmit it to everyone else
foreach (TcpClient otherClient in clientList.Values)
{
if (tc.Client.Handle != otherClient.Client.Handle)
{
Send(otherClient.GetStream(), text);
}
}
}
}
}
public void Send(NetworkStream ns, string data)
{
try
{
byte[] bdata = GetBytes(data, Encoding.ASCII);
ns.Write(bdata, 0, bdata.Length);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}
protected string GetNetworkString(NetworkStream ns)
{
if (ns.CanRead)
{
string receivedString;
byte[] b = GetNetworkData(ns);
receivedString = System.Text.Encoding.UTF8.GetString(b);
log.Info("Received string: " + receivedString);
return receivedString;
}
else
return null;
}
protected byte[] GetNetworkData(NetworkStream ns)
{
if (ns.CanRead)
{
log.Debug("Data detected on wire...");
byte[] b;
byte[] myReadBuffer = new byte[1024];
MemoryStream ms = new MemoryStream();
int numberOfBytesRead = 0;
// Incoming message may be larger than the buffer size.
do
{
numberOfBytesRead = ns.Read(myReadBuffer, 0, myReadBuffer.Length);
ms.Write(myReadBuffer, 0, numberOfBytesRead);
}
while (ns.DataAvailable);
//and get the full message
b = new byte[(int)ms.Length];
ms.Seek(0, SeekOrigin.Begin);
ms.Read(b, 0, (int)ms.Length);
ms.Close();
return b;
}
else
return null;
}
You will want to call HandleClients from a main thread that checks to see if there are any pending requests or not, and runs on a loop.

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