I have this code:
public static List<Socket> samp = new List<Socket>();
IPHostEntry host = null;
Socket sock;
host = Dns.GetHostEntry(sending ip..);
foreach (IPAddress address in host.AddressList)
{
IPEndPoint ipe = new IPEndPoint(address, 7777);
sock = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
sock.Connect(ipe);
if (sock.Connected)
{
samp.Add(sock);
}
}
This code work's okay. It send's my ip. How it looks in console:
How can I send custom string? For example i'm tried this code:
if (sock.Connected)
{
byte[] msg = Encoding.UTF8.GetBytes("This is a test");
byte[] bytes = new byte[256];
int i = sock.Send(msg);
MessageBox.Show(string.Format("Sent {0} bytes.", i));
samp.Add(sock);
}
It shows message: Sent 14 bytes. But in the console nothing prints.. How can I send this text to console? I'm also tried this:
sock.Send(Encoding.UTF8.GetBytes("This is a test"));
And this not prints :(
Thanks in advance !
Related
I have this code:
public static List<Socket> samp = new List<Socket>();
Socket connection/etc in form load..
IPHostEntry host = null;
Socket sock;
host = Dns.GetHostEntry(sending ip..);
foreach (IPAddress address in host.AddressList)
{
IPEndPoint ipe = new IPEndPoint(address, 7777);
sock = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
sock.Connect(ipe);
if (sock.Connected)
{
sock.SendTo(Encoding.UTF8.GetBytes("App starts"), ipe);
samp.Add(sock);
}
}
In form closing:
if (samp.Count > 0)
{
foreach (Socket socket in samp)
{
socket.Send(Encoding.UTF8.GetBytes("App closing"));
socket.Close();
}
}
And i'm getting error:
Cannot access a disposed object. Object name: 'System.Net.Sockets.Socket'
Thanks in advance!
P.S looks like socket.Close() works, but socket.Send nope :(
This is my code for a client to receive data from a server which is the simulator. While debugging the code, I received null values in this array, called receivedBytes:
// define buffer
byte[] receivedBytes = new byte[2048];
// define endpoint
IPHostEntry ipHost = Dns.Resolve("192.168.1.55");
IPAddress ipAddress = ipHost.AddressList[0];
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 1001);
// connect
Console.WriteLine("Starting: Creating Socket object");
Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sender.Connect(ipEndPoint);
Console.WriteLine("Successfully connected to {0}", sender.RemoteEndPoint);
// get user input
Console.WriteLine("Enter Client Message :");
string sendingMessage = Console.ReadLine();
// send
Console.WriteLine("Creating message:{0}", sendingMessage);
byte[] forwardMessage = Encoding.Default.GetBytes(sendingMessage);
sender.Send(forwardMessage);
// receive
int totalBytesReceived = sender.Receive(receivedBytes);
Console.WriteLine("Message provided from server: {0}", Encoding.Unicode.GetString(receivedBytes, 0, totalBytesReceived));
// close
sender.Shutdown(SocketShutdown.Both);
sender.Close();
Console.ReadLine();
What am I doing wrong here?
Actually the conversion code is wrong.
string sendingMessage = "Hello, World";
byte[] forwardMessage = Encoding.Default.GetBytes(sendingMessage);
string receivedMessage = Encoding.Unicode.GetString(forwardMessage, 0,forwardMessage.Length);
After that receivedMessage will be broken.
What it does? It gets default encoding to GetBytes and than uses UTF-16 encoding to get string. You should use Encoding.Default.GetBytes and Encoding.Default.GetString.
I have c# code which is connecting to localhost ip address 127.0.0.1 and port no. 5939. Connection is happening perfectly but it is not receiving any data. I want it to receive data and save it to text file on my local machine.
Does it not receiving data because it is on the localhost and on the same machine or there is error in my code ..
Here is my code..
byte[] data = new byte[1024];
string input, stringData;
String ip = "127.0.0.1";
Int32 port = 5939;
string path = "D://ipdata.text";
if (File.Exists("D://ipsettings.txt"))
{
File.Delete("D://ipsettings.txt");
}
IPAddress ipad = IPAddress.Parse(ip);
IPEndPoint ipend = new IPEndPoint(ipad, port);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
sock.Connect(ipend);
}
catch (Exception ex)
{
throw ex;
}
try
{
int recv = sock.Receive(data);
stringData = Encoding.ASCII.GetString(data, 0, recv);
while (true)
{
input = "Client here";
sock.Send(Encoding.ASCII.GetBytes(input));
data = new byte[1024];
recv = sock.Receive(data);
stringData = Encoding.ASCII.GetString(data, 0, recv);
string df = "";
try
{
System.IO.FileInfo fi = new System.IO.FileInfo(path);
My program is not executing after this line..
int recv = sock.Receive(data);
Please help me to get out of this situation.
Thanks in advance.
You need to read the data until unless the Receive function gives you.
use while loop to determine whether data is available or not.
int recv=0;
byte[] data = new byte[1024];
StringBuilder sb= new StringBuilder();
while ((recv=sock.Receive(data)) > 0)
{
sb.Append(Encoding.ASCII.GetString(data, 0, recv));
}
The function Dns.GetHostEntry doesn't handle ipaddresses as strings e.g. 127.0.0.1 but if I pass google.de as a parameter it works quite well.
Am I doing something wrong ?
public static Socket connSock(string Server, int Port)
{
Socket s = null;
IPHostEntry ipHE = Dns.GetHostEntry(Server);
//IPAddress[] ipA = null;
IPEndPoint ipE = null;
foreach (IPAddress address in ipHE.AddressList)
{
ipE = new IPEndPoint(address, Port);
Socket tempSocket = new Socket(ipE.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
tempSocket.Connect(ipE);
if (tempSocket.Connected)
{
s = tempSocket;
break;
}
else
{
continue;
}
}
return s;
}
This could mean you're system is unable to get the host entry. This occurs (for instance) when there's no PTR record defined for the given IP.
Iam trying to send a message (via UDP) from my client to my server. The server should answer this message and if the client receives this answer he should print out a message.
If i run the client and server on my local network everything works fine.
If i try to connect through the internet from another PC outside my network the server receives the request of the client, sends an answer back, but the client never receives this answer. The client and the server are both behind a NAT but i portforwarded the ports at the server´s NAT and the server got its own DNS. I already tried NAT traversal but it gives me the same IP and port adress as the IPEndPoint of the server, after receiveing the request of the client, does.
I´ve got no idea how to fix this, so any guidance would be much appreciated.
Client
public static void Main()
{
Thread receiveThread = new Thread(new ThreadStart(ReceiveData));
receiveThread.Start();
object[] oData = {1};
sendData(oData, 0,0, "Li");
while (true)
{
Console.ReadLine();
}
}
private void receiveData()
{
string receivePort = 8080;
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
client.ReceiveTimeout = 1000;
IPEndPoint end = new IPEndPoint(IPAddress.Any, receivePort);
client.Bind(end);
while (true)
{
try
{
byte[] data = new byte[1024];
client.Receive(data, 0, data.Length, SocketFlags.None);
object[] receivedObj = Deserialize(data);
string sType = (string)receivedObj[3];
if (sType == "Li")
{
console.WriteLine("received Li");
}
}
catch (Exception err)
{
Console.WriteLine(err.ToString());
}
}
}
public static void sendData(object[] oData, int iFrom, int iTo, string sType)
{
string sendPort = 17171;
UdpClient client = new UdpClient();
string IP = "ThisIsTheDNSofmyServer.com"; //ServerDNS
//string IP = "192.168.xxx.xxx"; //serverIP in LAN
if (IP.StartsWith("T"))
{
IP = (Dns.GetHostAddresses(IP))[0].ToString();
}
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(IP), sendPort);
oData[1] = iFrom;
oData[2] = iTo;
oData[3] = sType;
Byte[] data = Serialize(oData);
client.Send(data, data.Length, remoteEndPoint);
}
The server´s code is almost the same:
public static void Main()
{
Thread receiveThread = new Thread(new ThreadStart(ReceiveData));
receiveThread.Start();
while (true)
{
Console.ReadLine();
}
}
private static void ReceiveData()
{
int receivePort = 17171;
UdpClient client = new UdpClient(receivePort);
while (true)
{
try
{
IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
byte[] data = new byte[1024];
data = client.Receive(ref anyIP);
object[] receivedObj = Deserialize(data);
//if I receive data send an Answer
sendData(receivedObj, 0,0,"Li",anyIP.Address.ToString());
}
catch (Exception err)
{
Console.WriteLine(err.ToString());
}
}
}
private static void sendData(object[] oData, int iFrom, int iTo, string sType, string IP)
{
int sendPort = 8080;
object[] paket = { oData, iFrom, iTo, sType };
UdpClient client = new UdpClient();
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(IP), sendPort);
client.Send(data, data.Length, remoteEndPoint);
}
i believe this is a port cofniguration issue,
8080 is almost likely to be configured as alternate http
"The UdpClient you use to receive datagrams must be created using the multicast port number" from MSDN
Hope this helps and good luck
Krishna
You do not need to do anything unordinary to traverse NAT in the setup you described, you just need to send it from the server back to your client; specifically: you must send back to the end point, i.e. IP and port, you received it on.
client.Send(data, data.Length, remoteEndPoint); // remoteEndPoint is the IPEndPoint you got the datagram on