I am writing a basic TCP server/Client in C# and for some reason my server is not getting the data sent to it from the Client. and i cannot figure out why this is happening
static void Main(string[] args)
{
Console.WriteLine("Server Started");
int PORT = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["Port"]);
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, PORT);
Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
newsock.Bind(ipep);
newsock.Listen(10);
Socket client = newsock.Accept();
while (true)
{
byte[] data = new byte[1024];
int recv = client.Receive(data);
if (recv == 0) break;
string str = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine(str);
data = Encoding.ASCII.GetBytes(str.ToUpper());
client.Send(data, recv, SocketFlags.None);
}
client.Close();
newsock.Close();
Console.ReadLine();
}
And The client looks like this:
static void Main(string[] args)
{
Console.WriteLine("Starting Client");
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 80);
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
server.Connect(ipep);
}catch (SocketException e)
{Console.WriteLine("Unable to connect to Server" + e.ToString());}
while (true)
{
string input = Console.ReadLine();
if (input == "exit") break;
server.Send(Encoding.ASCII.GetBytes(input));
Console.WriteLine("Sent");
byte[] data = new byte[1024];
int recv = server.Receive(data);
Console.WriteLine("after client rec");
string stringData = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine(stringData);
}
server.Shutdown(SocketShutdown.Both);
server.Close();
}
}
Related
I am creating a TCP Server/Client. As for this project, i need to only run this function for 60 seconds, and after that, it will terminate. Can someone guide me to fix this code?
public static void SendTCPServer(string content)
{
Stopwatch timer = new Stopwatch();
timer.Start();
byte[] data = new byte[1024];
IPEndPoint ipep = new IPEndPoint(IPAddress.Any,
8080);
Socket newsock = new
Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
newsock.Bind(ipep);
newsock.Listen(10);
while (timer.Elapsed.TotalSeconds < 60)
{
Console.WriteLine("Waiting for a client...");
Socket client = newsock.Accept();
IPEndPoint clientep =
(IPEndPoint)client.RemoteEndPoint;
Console.WriteLine("Connected with {0} at port {1}",
clientep.Address, clientep.Port);
string welcome = content;
data = Encoding.ASCII.GetBytes(welcome);
client.Send(data, data.Length,
SocketFlags.None);
Console.WriteLine("Disconnected from {0}",
clientep.Address);
client.Close();
newsock.Close();
return;
}
timer.Stop();
//client.Close();
newsock.Close();
return;
}
You can use thread for this.
public class Parameters
{
public Socket _socket;
public string content;
}
//calling part
Thread listenerThread = new Thread(new ParameterizedThreadStart(SendTCPServer));
Socket newsock = new
Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
listenerThread.Start(new Parameters { _socket = newsock, content = "Welcome"
});
Thread.Sleep(60000);
newsock.Dispose();
//calling part end
public static void SendTCPServer(object obj)
{
try
{
Stopwatch timer = new Stopwatch();
timer.Start();
byte[] data = new byte[1024];
IPEndPoint ipep = new IPEndPoint(IPAddress.Any,
8080);
Parameters param = obj as Parameters;
Socket newsock = param._socket;
newsock.Bind(ipep);
newsock.Listen(10);
while (timer.Elapsed.TotalSeconds < 60)
{
Console.WriteLine("Waiting for a client...");
Socket client = newsock.Accept();
IPEndPoint clientep =
(IPEndPoint)client.RemoteEndPoint;
Console.WriteLine("Connected with {0} at port {1}",
clientep.Address, clientep.Port);
string welcome = param.content;
data = Encoding.ASCII.GetBytes(welcome);
client.Send(data, data.Length,
SocketFlags.None);
Console.WriteLine("Disconnected from {0}",
clientep.Address);
client.Close();
newsock.Close();
return;
}
timer.Stop();
//client.Close();
newsock.Close();
return;
}
catch (Exception ex)
{
}
}
I was wondering how i can manage that my Socket Server, that listens on port 3333 and for any incoming IP Addresses can listen for external connections. On my local network it all works fine, but if people try to connect to the server from another router they cant connect, i already added a Exception for my Server.exe in the Firewall and opened the Port 3333 on my router. Is there anything else i have to do?
Any help is appreciated
EDIT:
Server Code(C#):
private static Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
private static List<Socket> clientSockets = new List<Socket>();
private const int PORT = 3333;
private static byte[] buffer = new byte[100];
private static Random random = new Random();
private static int connectedClients = 0;
private void ReceiveCallback(IAsyncResult AR)
{
Socket current = (Socket)AR.AsyncState;
int received;
try
{
received = current.EndReceive(AR);
}
catch (SocketException)
{
Console.WriteLine("Client " + connectedClients + " Disconnected! (Forced)");
current.Close();
clientSockets.Remove(current);
return;
}
byte[] recBuf = new byte[100];
Array.Copy(buffer, recBuf, received);
string text = getText(Encoding.ASCII.GetString(recBuf));
if (text != "")
{
Console.WriteLine("Recieved: " + text);
}
if (current.Connected)
current.BeginReceive(buffer, 0, 100, SocketFlags.None, ReceiveCallback, current);
}
private void AcceptCallback(IAsyncResult AR)
{
Socket socket;
try
{
socket = serverSocket.EndAccept(AR);
}
catch (ObjectDisposedException)
{
return;
}
clientSockets.Add(socket);
socket.BeginReceive(buffer, 0, 100, SocketFlags.None, ReceiveCallback, socket);
connectedClients++;
Console.WriteLine("Client " + connectedClients + " Connected! [" + IPAddress.Parse(((IPEndPoint)socket.RemoteEndPoint).Address.ToString()) + "::" +
((IPEndPoint)socket.RemoteEndPoint).Port.ToString() + "]");
serverSocket.BeginAccept(AcceptCallback, null);
}
private void setupServer()
{
SocketPermission perm = new SocketPermission(NetworkAccess.Accept, TransportType.Tcp, ""/*Here would sit my IPv4*/, PORT);
perm.Assert();
serverSocket.Bind(new IPEndPoint(IPAddress.Any, PORT));
serverSocket.Listen(10);//0
Console.WriteLine("Server Started!");
Console.WriteLine("Listening for Clients...");
serverSocket.BeginAccept(AcceptCallback, null);
}
private void CloseAllSockets()
{
foreach (Socket socket in clientSockets)
{
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
serverSocket.Close();
}
static void Main(string[] args)
{
Console.Title = "Server";
Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.Green;
Program prgrm = new Program();
prgrm.setupServer();
Console.ReadLine();
prgrm.CloseAllSockets();
}
I'm connecting to my server on the internal network. But I cannot connect to a server on an external network. The server's firewall on the external network closed. The port forwarding server was.
Server side codes:
private byte[] _buffer = new byte[1024];
private List<Socket> _clientSockets = new List<Socket>();
private Socket _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
public int PortNo;
private void SetupServer()
{
try
{
_serverSocket.Bind(new IPEndPoint(IPAddress.Any, PortNo));
_serverSocket.Listen(1);
_serverSocket.BeginAccept(new AsyncCallback(AcceptCallBack), null);
}
catch(Exception hata)
{
MessageBox.Show(hata.Message);
}
}
private void AcceptCallBack(IAsyncResult AR)
{
Socket socket = _serverSocket.EndAccept(AR);
_clientSockets.Add(socket);
try
{
socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), socket);
_serverSocket.BeginAccept(new AsyncCallback(AcceptCallBack), null);
}
catch(Exception hata)
{
MessageBox.Show(hata.Message);
}
}
private void ReceiveCallBack(IAsyncResult AR)
{
Socket socket = (Socket)AR.AsyncState;
int received = socket.EndReceive(AR);
byte[] dataBuf = new byte[received];
Array.Copy(_buffer, dataBuf, received);
string text = Encoding.ASCII.GetString(dataBuf);
byte[] response = response = ekranGonderme();
try
{
socket.BeginSend(response, 0, response.Length, SocketFlags.None, new AsyncCallback(SendCallBack), null);
socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), socket);
}
catch(Exception hata)
{
MessageBox.Show(hata.Message);
}
}
Client Side Codes:
private static Socket _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
int portNo = 20000;
IPAddress[] server_ip = Dns.GetHostAddresses(server's external ip address);
private void Form1_Load(object sender, EventArgs e)
{
LoopConnect();
LoopSendReceive()
}
private void LoopSendReceive()
{
try
{
byte[] buffer = Encoding.ASCII.GetBytes("ekran_iste");
_clientSocket.Send(buffer);
byte[] receiveBuf = new byte[999999];
int rec = _clientSocket.Receive(receiveBuf);
byte[] data = new byte[rec];
Array.Copy(receiveBuf, data, rec);
MemoryStream ms = new MemoryStream(data);
}
catch
{
}
}
private void LoopConnect()
{
int attempts = 0;
while (!_clientSocket.Connected)
{
try
{
attempts++;
_clientSocket.Connect(server_ip[0], portNo);
}
catch(SocketException)
{
}
}
}
}
OK, so I am not very good at programming in general, but I want to try my hand at using sockets. To start I watched a Youtube video which I followed step by step, I got the finished product working 100% to the guides however I wish to modify it in order for the server to be able to send a message to all connected clients.
Here is the youtube video: Youtube Video - Sockets
So this is the code for the server class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
namespace Server
{
class Program
{
private static byte[] buffer = new byte[1024];
public static Socket _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
public static List<Socket> clientSockets = new List<Socket>();
static void Main(string[] args)
{
Console.Title = "Server, " + clientSockets.Count.ToString() + " clients are connected";
SetupServer();
Console.ReadLine();
}
public static void SetupServer()
{
Console.WriteLine("Setting up server...");
_serverSocket.Bind(new IPEndPoint(IPAddress.Any, 100));
_serverSocket.Listen(5);
_serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
}
public static void AcceptCallback(IAsyncResult AR)
{
Socket socket = _serverSocket.EndAccept(AR);
clientSockets.Add(socket);
Console.WriteLine("Client Connected");
Console.Title = "Server, " + clientSockets.Count.ToString() + " clients are connected";
socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(RecieveCallBack), socket);
_serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
}
private static void RecieveCallBack(IAsyncResult AR)
{
Socket socket = (Socket)AR.AsyncState;
int received = socket.EndReceive(AR);
byte[] databuff = new byte[received];
Array.Copy(buffer, databuff, received);
string s = Encoding.ASCII.GetString(databuff);
Console.WriteLine("Text Received: " + s);
string response = string.Empty;
if (s.ToLower() == "get time")
{
response = DateTime.Now.ToLongTimeString();
}
else
{
response = "Invalid Request";
}
byte[] data = Encoding.ASCII.GetBytes(response);
socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(sendCallback), socket);
socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(RecieveCallBack), socket);
}
private static void sendCallback(IAsyncResult AR)
{
Socket socket = (Socket)AR.AsyncState;
socket.EndSend(AR);
}
}
}
I had a pretty pathetic attempt at what I wanted to do:
private static void RecieveCallBack(IAsyncResult AR)
{
Socket socket = (Socket)AR.AsyncState;
int received = socket.EndReceive(AR);
byte[] databuff = new byte[received];
Array.Copy(buffer, databuff, received);
string s = Encoding.ASCII.GetString(databuff);
Console.WriteLine("Text Received: " + s);
foreach(Socket s1 in clientSockets){
string response = string.Empty;
if (s.ToLower() == "get time")
{
response = DateTime.Now.ToLongTimeString();
}
else
{
response = "Invalid Request";
}
byte[] data = Encoding.ASCII.GetBytes(response);
s1.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(sendCallback), s1);
s1.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(RecieveCallBack), s1);
}
}
wasn't really expecting it too work, but I gave it a go.
Another secondary question:
Is this the line of code which determines what IP and Port the server will be listening on?
_serverSocket.Bind(new IPEndPoint(IPAddress.Any, 100));
Used the same code, had the same problem.
It is not working because the client console is stuck in readLine(), so it is not receiving responses. After you send a command don't call Console.ReadLine again.
To loop trough all clients and send a message:
private static void sentToAll(string s)
{
foreach (Socket socket in clientSockets)
{
byte[] data = Encoding.ASCII.GetBytes(s);
socket.Send(data);
}
}
private static IPEndPoint localEndPoint;
public static String IpAddress = "10.0.0.13";
public static int port = 3000;
localEndPoint = new IPEndPoint(IPAddress.Parse(IpAddress), port);
_serverSocket.Bind(localEndPoint);
Am trying to make a simple UDP application using C sharp,nothing sophisticated,connect,send some text,and receive it! but it keeps throwing this exception!
"An existing connection was forcibly closed by the remote host"!
The code :
byte[] data = new byte[1024];
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
string welcome = "Hello, are you there?";
data = Encoding.ASCII.GetBytes(welcome);
server.SendTo(data, data.Length, SocketFlags.None, ipep);
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint tmpRemote = (EndPoint)sender;
data = new byte[1024];
int recv = server.ReceiveFrom(data, ref tmpRemote);
Console.WriteLine("Message received from {0}:", tmpRemote.ToString());
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
Console.WriteLine("Stopping client");
server.Close();
thanks =)
You should tell the system that you are listening for UDP packets on port 9050 before you call Receive.
Add server.Bind(ipep); after Socket server = new Socket(...);
Have you tried checking that the IP address is valid and the port is not being used for something else?
Windows:
Start > Run > "cmd" > "ipconfig".
Try turning off your firewall software.
If you do not know the IP of the answering server, you better do:
recv = server.Receive(data);
Here is my suggetion to your code. You can use a do-while loop using a condition (in my example it is an infinite loop):
byte[] data = new byte[1024];
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
string welcome = "Hello, are you there?";
data = Encoding.ASCII.GetBytes(welcome);
server.ReceiveTimeout = 10000; //1second timeout
int rslt = server.SendTo(data, data.Length, SocketFlags.None, ipep);
data = new byte[1024];
int recv = 0;
do
{
try
{
Console.WriteLine("Start time: " + DateTime.Now.ToString());
recv = server.Receive(data); //the code will be stoped hier untill the time out is passed
}
catch { }
} while (true); //carefoul! infinite loop!
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
Console.WriteLine("Stopping client");
server.Close();