I am new to socket programming in C#. Have searched the web like crazy for the solution to my problem but didnt find anything that could fix it. So heres my problem:
I am trying to write a client-server application. For the time being, the server will also run on my local machine. The application transmits a byte stream of data from the client to the server. The problem is that the server doesnt detect a client request for connection, while the client is able to connect and transmit the byte stream.
here is the server code:
String strHostName = Dns.GetHostName();
Console.WriteLine(strHostName);
IPAddress ip = IPAddress.Parse("127.0.0.1");
ipEnd = new IPEndPoint(ip, port);
soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
soc.Bind(ipEnd);
Console.WriteLine("Web Server Running... Press ^C to Stop...");
Thread th = new Thread(new ThreadStart(StartListen));
th.Start();
The StartListen thread is as below:
public void StartListen()
{
try
{
while (true)
{
string message;
Byte[] bSend = new Byte[1024];
soc.Listen(100);
if (soc.Connected)
{
Console.WriteLine("\nClient Connected!!\n==================\n CLient IP {0}\n", soc.RemoteEndPoint);
Byte[] bReceive = new Byte[1024 * 5000];
int i = soc.Receive(bReceive);
The client code is as follows:
hostIPAddress = IPAddress.Parse("127.0.0.1");
ipEnd = new IPEndPoint(hostIPAddress,port);
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
Console.WriteLine("Connecting to Server...");
clientSocket.Connect(ipEnd);
Console.WriteLine("Sending File...");
clientSocket.Send(clientData);
Console.WriteLine("Disconnecting...");
clientSocket.Close();
Console.WriteLine("File Transferred...");
Now what happens is that the server starts and when I run the client, it connects, sends and closes. But nothing happens on the server console, it doesnt detect any connection: if (soc.Connected) remains false.
I checked whether the server was listening to 127.0.0.1:5050 through netstat, and it sure was listening. Cant figure out the problem. Please help.
On the server side use Socket.Accept Method to accept incoming connection. The method returns a Socket for a newly created connection: the Send() and Receive() methods can be used for this socket.
For example, after accepting the separate thread can be created to process the client connection (i.e. client session).
private void ClientSession(Socket clientSocket)
{
// Handle client session:
// Send/Receive the data.
}
public void Listen()
{
Socket serverSocket = ...;
while (true)
{
Console.WriteLine("Waiting for a connection...");
var clientSocket = serverSocket.Accept();
Console.WriteLine("Client has been accepted!");
var thread = new Thread(() => ClientSession(clientSocket))
{
IsBackground = true
};
thread.Start();
}
}
Related
So I'm trying to create a chat application but I'm new to sockets. I have followed a tutorial to create a server and client, however, the server does not broadcast the data sent from one client to every client connected to it. Instead, it only broadcasts it to the client that sent the data.
I have tried to add every client who joins the server to a list and then use a foreach loop to send the data received from one client to every client in the list. This, however, has not worked. I suspect that the error is in the foreach loop but I am not completely certain.
Here is my code for the server:
class Program
{
public static List<Socket> connectedClient = new List<Socket>();
public static Socket clientSocket = default(Socket);
static void Main(string[] args)
{
int port = 13000;
string IpAddress = "127.0.0.1";
Socket serverListener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ep = new IPEndPoint(IPAddress.Parse(IpAddress), port);
serverListener.Bind(ep);
serverListener.Listen(0);
Console.WriteLine("Server running");
Program p = new Program();
int counter = 0;
while (true)
{
counter++;
clientSocket = serverListener.Accept();
connectedClient.Add(clientSocket);
Console.WriteLine(counter + " Client joined");
Thread clientThread = new Thread(new ThreadStart(() =>
p.User(clientSocket)));
clientThread.Start();
}
}
public void User(Socket client)
{
while (true)
{
byte[] msg = new byte[1024];
int size = client.Receive(msg);
Console.WriteLine("Client>> " +
System.Text.Encoding.ASCII.GetString(msg, 0, size));
//the loop that i tried to implement
foreach(Socket clientSocket in connectedClient)
{
client.Send(msg, 0, size, SocketFlags.None);
}
}
}
}
Instead of the message being broadcasted once to all clients, the server sends the message back to the client who sent it but times how many clients there are.
For example: If there are 4 clients connected to the server and one client sends a message "Hello" the server will send back "HelloHelloHelloHello" but only to the client who sent the "Hello".
In
foreach(Socket clientSocket in connectedClient)
{
client.Send(msg, 0, size, SocketFlags.None);
}
You are looping over the clientSockets, but you are Sending on the client, not the clientSocket. If you do clientSocket.Send instead, you should get the expected behavior (e.g. send to each client instead of to one client 4 times).
I'm working on a UDP Server-Client application.
When I create a new client, the client connect to the server and they begin to exchange data
This is my client constructor:
static EndPoint serverEP;
static Socket clientSocket;
public Client(Player client)
{
clientSocket = clientSocket = new Socket(
AddressFamily.InterNetwork,
SocketType.Dgram,
ProtocolType.Udp);
clientSocket.Bind(new IPEndPoint(IPAddress.Any,0));
clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
serverEP = new IPEndPoint(IPAddress.Parse(Server.serverIp), port);
}
After few actions I want to connect to another server.
My question is, is it possible to change port in the socket client?
I have tried this but it does not work, the program stay stuck:
public void changePort(int newPort)
{
clientSocket.Bind(new IPEndPoint(IPAddress.Any, 0));
serverEP = new IPEndPoint(IPAddress.Parse(Server.serverIp), newPort);
}
It is a solution to close a socket like this:
public void CloseSocket()
{
clientSocket.Shutdown(SocketShutdown.Send);
clientSocket.Close();
}
and start a new client on the new Port ?
Have a large slow feed over a .NET asynchronous socket. Data is coming from instruments so can be 1 row a second (or more). Some times it can just stall.
Using there two examples from MSDN
asynchronous-client-socket-example
asynchronous-server-socket-example
I have a requirement from the socket client stop the transfer from the server mid stream. Each message is pretty small. Do not need to stop mid message. Need to be able to stop the loop - can receive 1000s of small messages (to client).
My thought is to save a reference to client and call:
client.Shutdown(SocketShutdown.Both);
client.Close();
Is this the correct approach?
private static Socket client;
private static void StartClient()
{
// Connect to a remote device.
try
{
// Establish the remote endpoint for the socket.
// The name of the
// remote device is "host.contoso.com".
//IPHostEntry ipHostInfo = Dns.GetHostEntry("host.contoso.com"); Dns.GetHostName()
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
// Create a TCP/IP socket.
Socket client = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
//client = new Socket(ipAddress.AddressFamily,
// SocketType.Stream, ProtocolType.Tcp);
// Connect to the remote endpoint.
client.BeginConnect(remoteEP,
new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne();
// Send test data to the remote device.
Send(client, "This is a test<EOF>");
sendDone.WaitOne();
// Receive the response from the remote device.
Receive(client);
receiveDone.WaitOne();
// Write the response to the console.
Console.WriteLine("Response received : {0}", response);
// Release the socket.
client.Shutdown(SocketShutdown.Both);
client.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
I have found this piece of code on the internet: it does not open a server listening on port 11000, as I hoped.
What can be the problem? I normally code in Delphi, so I am little lost. I have made a corresponding client in Delphi, which works.
I am using demo version of C# 2015.
public static void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
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(localEndPoint);
listener.Listen(10);
// Start listening for connections.
while (true)
{
//Console.WriteLine("Waiting for a connection...");
// Program is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
data = null;
// An incoming connection needs to be processed.
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf("#") > -1)
{
break;
}
}
// Show the data on the console.
//Console.WriteLine("Text received : {0}", data);
// Echo the data back to the client.
byte[] msg = Encoding.ASCII.GetBytes(data);
handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
//Console.WriteLine("\nPress ENTER to continue...");
//Console.Read();
}
The problem might be here: Whats the IP address of ipHostInfo.AddressList[0] ? It might be the loop-back. I never restrict my server endpoint to an ip-adress unless I need to, but then I will specify it in a configfile.
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 11000);
As per Jeroen's answer, encountered per .NET's Synchronous Server Socket Example. When listening/connecting to localhost, one should rather use
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
instead of
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
Thanks for feedback. I found som other, older code:
TcpListener serverSocket = new TcpListener(11000);
that does the job. I know it is depreciated, but it works, actually.
I'm creating a small chat (1-1) application to learn network programming and when creating the socket using TCP protocol, the Socket.Connect() always return error 10061.
However, if I make the socket UDP, I don't see the issue.
Here is my code:
myEndPoint = new IPEndPoint(IPAddress.Parse(_txtMyIPAdress.Text), int.Parse(_txtMyPort.Text));
TargetSideEndPoint = new IPEndPoint(IPAddress.Parse(_txtTargetIPAddress.Text), int.Parse(_txtTargetPort.Text));
mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
mySocket.Bind(myEndPoint);
mySocket.Connect(TargetSideEndPoint);
byte[] receivedBuffer = new byte[MAX_BUFFER_SIZE = 1024];
ReceivePackets(mySocket, receivedBuffer);//My function
Can any one help me?
Update:
I'm not using Listen() the issue is when I call Connect()
I already tried multiple ports with the same issue and I'm currently testing on 1 PC by opening 2 instances from my application and using 2 different ports while firewall is off.
Thanks,
For TCP, which is a connection oriented protocol, you would need a server and a client.
The server must listen for incoming connections and the client should initiate the connection. Then, the client will be able to communicate with the server and exchange data.
Here is a simple working example:
void Main()
{
Console.WriteLine("Starting listener thread");
Thread serverThread = new Thread(ListenerThreadProc);
serverThread.Start();
Console.WriteLine("Waiting 500 milliseconds to allow listener to start");
Thread.Sleep(500);
Console.WriteLine("Client: Connecting to server");
TcpClient client = new TcpClient();
client.Connect(IPAddress.Loopback, 12345);
Console.WriteLine("Client: Connected to server");
byte[] buffer = new byte[5];
Console.WriteLine("Client: Receiving data");
using (NetworkStream clientStream = client.GetStream())
clientStream.Read(buffer, 0, buffer.Length);
Console.WriteLine("Client: Received data: " + buffer.Aggregate("", (s, b) => s += " " + b.ToString()));
}
void ListenerThreadProc()
{
TcpListener listener = new TcpListener(IPAddress.Any, 12345);
listener.Start();
Console.WriteLine("Server: Listener started");
Console.WriteLine("Server: Waiting for client to connect");
TcpClient client = listener.AcceptTcpClient();
Console.WriteLine("Server: Client connected");
listener.Stop();
Console.WriteLine("Server: Listener stopped");
Console.WriteLine("Server: Sending data");
byte[] buffer = new byte[] { 1, 2, 3, 4, 5 };
using (NetworkStream clientStream = client.GetStream())
clientStream.Write(buffer, 0, buffer.Length);
Console.WriteLine("Server: Sent data");
}
In this example, made as simple as it gets, you have a server accepting a single client to which it sends some data. The client connects, reads the data and then displays it.
A real-life server would spin new threads (or tasks, for async model) to serve the client's request as soon as the client would connect and carry on listening for new connections.