How to end the loop on timeout, TCPServer Socket C# - c#

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)
{
}
}

Related

Save connected Socket in Dictionary

I'm trying to save a connected socket in a dictionary so my API doesn't have to create a new connection every time. My problem is that the socket gets disposed.
So when I call GetConnection() a second time socket.connected is false and socket.Available.Message is "Cannot access a disposed object. Object name: 'System.Net.Sockets.Socket'.".
public static class ModbusSocket
{
private static Dictionary<IPAddress, Socket> socketList;
public static Socket GetConnection(string server, int port)
{
if (socketList is null)
{
socketList = new Dictionary<IPAddress, Socket>();
}
IPAddress iPAddress = IPAddress.Parse(server);
if (socketList.ContainsKey(iPAddress))
{
var socket = socketList[iPAddress];
if (socket.Connected)
{
return socket;
}
else
{
socketList.Remove(iPAddress);
socket = new Socket(iPAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipe = new IPEndPoint(iPAddress, port);
socket.Connect(ipe);
socketList.Add(iPAddress, socket);
return socket;
}
}
else
{
Socket socket = new Socket(iPAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipe = new IPEndPoint(iPAddress, port);
socket.Connect(ipe);
socketList.Add(iPAddress, socket);
return socket;
}
}
}
OMG I found the issue...
I invoked it with using:
using (Socket s = ModbusSocket.GetConnection(hostIp, port))
{
var telegram = new Telegram();
telegram.Set(0, AddressConst.PositionWindow, 4);
var response = telegram.SendAndReceive(s);
var result = BitConverter.ToInt32(new byte[] { response.Byte19, response.Byte20, response.Byte21, response.Byte22 }, 0);
return result;
}

c# socket connection with multi threading telnet

**i use c# this code socket connection with multi threading **
i need set time out to my socket connection telnet
string ip = "";
int port = 23;
string str = "";
IPAddress address = IPAddress.Parse(ip);
IPEndPoint ipEndPoint = new IPEndPoint(address, port);
Socket socket = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
socket.Connect((EndPoint)ipEndPoint);
try
{
byte[] numArray = new byte[1024];
while (socket.Connected) {
int count = socket.Receive(numArray);
str += Encoding.ASCII.GetString(numArray, 0, count);
Console.WriteLine(str);
}
socket.Close();
}
catch (ArgumentNullException ex)
{
}
You can either create a timer to do this or what I like to do is give the socket.connected a timeframe and base my connection of that. You'd obviously need to modify the time per your conditions, but this example has worked for me in the past.
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Connect using a timeout (5 seconds)
IAsyncResult result = socket.BeginConnect( iP, iPort, null, null );
bool success = result.AsyncWaitHandle.WaitOne( 5000, true );
if ( socket.Connected )
{
socket.EndConnect( result );
}
else
{
//Be sure to close socket
socket.Close();
throw new ApplicationException("Failed to connect the server. Try again.");
}
I saw another example someone else did with timer, but I have not personally used this, so whichever you are more comfortable with. start a timer (timer_connection), if time is up, check whether socket connection is connected (if(m_clientSocket.Connected)), if not, pop up timeout error
private void connect(string ipAdd,string port)
{
try
{
SocketAsyncEventArgs e=new SocketAsyncEventArgs();
m_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ip = IPAddress.Parse(serverIp);
int iPortNo = System.Convert.ToInt16(serverPort);
IPEndPoint ipEnd = new IPEndPoint(ip, iPortNo);
//m_clientSocket.
e.RemoteEndPoint = ipEnd;
e.UserToken = m_clientSocket;
e.Completed+=new EventHandler<SocketAsyncEventArgs>(e_Completed);
m_clientSocket.ConnectAsync(e);
if (timer_connection != null)
{
timer_connection.Dispose();
}
else
{
timer_connection = new Timer();
}
timer_connection.Interval = 2000;
timer_connection.Tick+=new EventHandler(timer_connection_Tick);
timer_connection.Start();
}
catch (SocketException se)
{
lb_connectStatus.Text = "Connection Failed";
MessageBox.Show(se.Message);
}
}
private void e_Completed(object sender,SocketAsyncEventArgs e)
{
lb_connectStatus.Text = "Connection Established";
WaitForServerData();
}
private void timer_connection_Tick(object sender, EventArgs e)
{
if (!m_clientSocket.Connected)
{
MessageBox.Show("Connection Timeout");
//m_clientSocket = null;
timer_connection.Stop();
}
}

Get Socket Server to listen for external Connections

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();
}

C# Server not receiving data

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();
}
}

Cannot connect to server with external ip via socket.connect() in c#

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)
{
}
}
}
}

Categories