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.
Related
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.
I have an udp client server source on C# and now I have a problem: I test my source on localhost but it doesn't receive on long way connections for example a VPS to a client.
Client:
private static void StartListener()
{
bool done = false;
UdpClient listener = new UdpClient(listenPort);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
try
{
while (!done)
{
byte[] bytes = listener.Receive(ref groupEP);
Thread.Sleep(100);
byte[] dcbufresponse = new byte[512];
dcbufresponse = Encoding.ASCII.GetBytes("0xc00901");
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(ipaddresssv), 9052);
s.SendTo(dcbufresponse, dcbufresponse.Length, SocketFlags.None, ipep);
done = true;
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{
listener.Close();
}
}
Server :
private static Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
private static IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(ipnow), 9052);
s.SendTo(dcbuf, dcbuf.Length, SocketFlags.None, ipep);
Console.WriteLine("sended");
sended.Add(ipnow);
try
{
listener.Client.ReceiveTimeout = 5000;
byte[] bytes = listener.Receive(ref groupEP);
string dcresponse = Encoding.ASCII.GetString(bytes, 0, bytes.Length);
Console.WriteLine(dcresponse);
}
Problem is this : client doesn't receive anything and client can not send to server after receiving ...
Edit :
My Serve Have Two Ip Address !
and i thinking that i must bind once of my two ip address to my udp client :-?
do you think that its work ?
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.
I have a program that multiple clients would be able to connect to a server using a socket:
private void performConnect()
{
while (true)
{
if (myList.Pending())
{
thrd = thrd + 1;
tcpClient = myList.AcceptTcpClient();
IPEndPoint ipEndPoint = (IPEndPoint)tcpClient.Client.RemoteEndPoint;
string clientIP = ipEndPoint.Address.ToString();
nStream[thrd] = tcpClient.GetStream();
currentMsg = "\n New IP client found :" + clientIP;
recieve[thrd].Start();
this.Invoke(new rcvData(addNotification));
try
{
addToIPList(clientIP);
}
catch (InvalidOperationException exp)
{
Console.Error.WriteLine(exp.Message);
}
Thread.Sleep(1000);
}
}
}
then the server could send data (chat messages) to a chosen client, using this code.
private void sendData(String data)
{
IPAddress ipep =IPAddress.Parse(comboBox1.SelectedItem.ToString());
Socket server = new Socket(AddressFamily.InterNetwork , SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipept = new IPEndPoint( ipep, hostPort);
NetworkStream nStream = tcpClient.GetStream();
ASCIIEncoding asciidata = new ASCIIEncoding();
byte[] buffer = asciidata.GetBytes(data);
if (nStream.CanWrite)
{
nStream.Write(buffer, 0, buffer.Length);
nStream.Flush();
}
}
the problem is that whatever IP i choose from the combo box, the message i send would always be directed/sent to the last IP that connected to the server.. Please somebody pinpoint my error! all help would be appreciated.
Look at those lines:
IPAddress ipep =IPAddress.Parse(comboBox1.SelectedItem.ToString());
Socket server = new Socket(AddressFamily.InterNetwork , SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipept = new IPEndPoint( ipep, hostPort);
NetworkStream nStream = tcpClient.GetStream();
You are creating a new socket but you are sending the data to the socket stored in the variable tcpClient that is global (since it was not defined in the method), thus totally ignoring the IPEndPoint parsed from the combobox.
You should not create a new socket in order to send data to the clients. Instead, store all clients in a collection and retrieve the appropriate one based on the input of the combobox.
I am testing this locally, so the IP to connect to can be localhost or 127.0.0.1
After sending it, it receives a string back. That would also be handy.
Socket soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(server);
System.Net.IPEndPoint remoteEP = new IPEndPoint(ipAdd, 3456);
soc.Connect(remoteEP);
For connecting to it.
To send something:
//Start sending stuf..
byte[] byData = System.Text.Encoding.ASCII.GetBytes("un:" + username + ";pw:" + password);
soc.Send(byData);
And for reading back..
byte[] buffer = new byte[1024];
int iRx = soc.Receive(buffer);
char[] chars = new char[iRx];
System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
int charLen = d.GetChars(buffer, 0, iRx, chars, 0);
System.String recv = new System.String(chars);
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipAdd = System.Net.IPAddress.Parse(m_ip);
IPEndPoint remoteEP = new IPEndPoint(ipAdd, m_port);
socket.Connect(remoteEP);
byte[] byData = System.Text.Encoding.ASCII.GetBytes("Message");
socket.Send(byData);
socket.Disconnect(false);
socket.Close();