Reconnecting to an unclosed Socket connection C# - c#

I have a Listener application which expects a string message for display. I cannot modify this application.
I have to send messages to this listener through my C# client. Both the listener and client are supposed to run on the same PC (local host).
My Code to Connect:
public void ConnectAndSendMessage(string MessageToSend)
{
string localIP = GetIPAddress();
try
{
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("Connecting.....");
tcpclnt.Connect(localIP, 2400);
Socket socket = tcpclnt.Client;
bool connectionStatus = socket.Connected;
if (connectionStatus)
{
//Send Message
ASCIIEncoding asen = new ASCIIEncoding();
//string sDateTime = DateTime.Now.ToString();
int SendStatus = socket.Send(asen.GetBytes(MessageToSend + Environment.NewLine));
}
Thread.Sleep(2000);
tcpclnt.Close();
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
}
Problem:
The client application runs fine and send the messages successfully to the Listener. But the problem comes if the client gets crashed (I close the client program) before executing tcpclnt.Close();. In this case, if I restart the Client program again then, I cannot connect to the socket since the application didn’t close the socket in the previous run (crashed run).
How can I reconnect to the listener in this condition?

try this one..
public void ConnectAndSendMessage(string MessageToSend)
{
string localIP = GetIPAddress();
using (System.Net.Sockets.TcpClient tcpclnt = new System.Net.Sockets.TcpClient())
{
try
{
Console.WriteLine("Connecting.....");
tcpclnt.Connect(localIP, 2400);
using (System.Net.Sockets.Socket socket = tcpclnt.Client)
{
if (socket.Connected)
{
//Send Message
System.Text.ASCIIEncoding asen = new System.Text.ASCIIEncoding();
//string sDateTime = DateTime.Now.ToString();
int SendStatus = socket.Send(asen.GetBytes(MessageToSend + Environment.NewLine));
}
System.Threading.Thread.Sleep(2000);
}
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
finally
{
if (tcpclnt != null && tcpclnt.Connected)
tcpclnt.Close();
}
}
}

Related

C# Winforms using TcpListener I can't connect to server from other devices on my LAN

I have a Winforms application that's going to transfers data to an Android application, for now it accepts a connection and displays a line of text as output. I tested on my local machine using the telnet command in PowerShell and it returns the correct message. When I tried the command from another PC on my network, it just times out and fails to connect. I made sure the port was free and that my firewall was turned off.
Here is my method:
public void senddata()
{
new Thread(() =>
{
Thread.CurrentThread.IsBackground = true;
TcpListener server = null;
try
{
Int32 port = 4296;
IPAddress localAddr =IPAddress.Any;
server = new TcpListener(localAddr, port);
server.Start();
Byte[] bytes = new Byte[256];
while (true)
{
server.Start();
Debug.WriteLine("Waiting for a connection... ");
TcpClient client = server.AcceptTcpClient();
NetworkStream stream = client.GetStream();
Debug.WriteLine("Connected!");
server.Stop();
while (stream.Read(bytes, 0, bytes.Length) != 0)
{
string data = "CPU: " + cpuCircle.Value + " C" + " | GPU: " + gpuCircle.Value + " C";
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
stream.Write(msg, 0, msg.Length);
stream.Flush();
}
client.Close();
}
}
catch (SocketException m)
{
Debug.WriteLine("SocketException: "+m);
}
finally
{
server.Stop();
}
}).Start();
}
Any idea what I'm doing wrong?
I think the main issue is that your listener object is being created in Thread itself due to which only first client able to connect. Please make TcpListener object before calling senddata() method and this listener should accept connection before calling senddata() method as well and pass client object to senddata(TcpClient client) method. By doing so you would be able to entertain theoretically unlimited clients simultanously:
Try This:
void StackOverflow4() // Your calling method
{
TcpListener server = null;
Int32 port = 4296;
IPAddress localAddr = IPAddress.Any;
try
{
server = new TcpListener(localAddr, port);
server.Start();
Byte[] bytes = new Byte[256];
while (true)
{
Debug.WriteLine("Waiting for a connection... ");
TcpClient client = server.AcceptTcpClient();
senddata(client);
}
}
catch (SocketException m)
{
Debug.WriteLine("SocketException: " + m);
//Some logic to restart listner
}
catch(Exception ex)
{
Debug.WriteLine(ex.Message);
//Some logic to restart listner
}
}
public void senddata(TcpClient client)
{
new Thread(() =>
{
Thread.CurrentThread.IsBackground = true;
try
{
Byte[] bytes = new Byte[256];
while (true)
{
NetworkStream stream = client.GetStream();
Debug.WriteLine("Connected!");
//server.Stop();
while (stream.Read(bytes, 0, bytes.Length) != 0)
{
string data = "CPU: " + cpuCircle.Value + " C" + " | GPU: " + gpuCircle.Value + " C";
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
stream.Write(msg, 0, msg.Length);
stream.Flush();
}
client.Close();
}
}
catch (SocketException m)
{
Debug.WriteLine("SocketException: " + m);
}
finally
{
//server.Stop();
}
}).Start();
}

C# TCP Application won't work

I'm making a simple chat application using TcpClient and TcpServer from System.Net.
I got everything working on my PC, the server communicates with the client and vice versa. But when I try to connect to the same server application using another PC (even on the same subnet as my PC) the thing doesn't work.
I've tried port-forwarding through my router, firewall and still nothing.
The Can you see me website says that the connection is being refused. Although!! Sometimes it says that the connection is timed out completely.
I am not sure what's wrong with my code or my PC, I would really appreciate some help from people that are more experienced in this area than I am.
Here is the configuration for the port forwarding in my router:
If you need the code for the client and the server, here they are:
P.S. I make the change to the client in the BeginConnect() part at the bottom in order to change the IP address that I'm connecting to
Client:
using System;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
namespace TcpTest_Client_
{
public partial class Form1 : Form
{
TcpClient client;
IPAddress localIP = null;
bool connected = false;
public Form1()
{
InitializeComponent();
}
public void clientConnectCallback(IAsyncResult result)
{
try
{
client.EndConnect(result);
Log("Connected to " + client.Client.RemoteEndPoint);
connected = true;
NetworkStream clientStream = client.GetStream();
byte[] message = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = 0;
try
{
//blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch (Exception ex)
{
//a socket error has occured
Log(ex.Message);
break;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
Log("Server on has disconnected");
break;
}
//message has successfully been received
UTF8Encoding encoder = new UTF8Encoding();
string bufferincmessage = encoder.GetString(message, 0, bytesRead);
Log("Server: " + bufferincmessage);
}
}
catch (Exception ex)
{
Log(ex.Message);
}
}
public void Log(string msg)
{
richTextBox1.BeginInvoke(new Action(
() =>
{
richTextBox1.Text += msg + "\n";
}));
}
private void Form1_Load(object sender, EventArgs e)
{
foreach (IPAddress addr in Dns.GetHostAddresses(Dns.GetHostName()))
{
if (addr.AddressFamily == AddressFamily.InterNetwork)
{
localIP = addr;
break;
}
}
client = new TcpClient(AddressFamily.InterNetwork);
}
private void button2_Click(object sender, EventArgs e)
{
try
{
client.BeginConnect(IPAddress.Parse("109.252.107.144"), 1234, clientConnectCallback, client);
}
catch (Exception ex)
{
Log(ex.Message);
}
}
private void button1_Click(object sender, EventArgs e)
{
if (connected)
{
UTF8Encoding encoder = new UTF8Encoding();
NetworkStream clientStream = client.GetStream();
byte[] stringToSend = new byte[richTextBox2.Text.Length];
stringToSend = encoder.GetBytes(richTextBox2.Text);
clientStream.Write(stringToSend, 0, stringToSend.Length);
}
}
}
}
Server:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace TcpTest
{
public partial class Form1 : Form
{
private TcpListener server;
private List<Thread> clientThreads = null;
public Thread MainThread;
public Form1()
{
InitializeComponent();
}
public void Log(string msg)
{
richTextBox1.BeginInvoke(new Action(
() =>
{
richTextBox1.Text += msg + "\n";
}));
}
public static string bufferincmessage;
public void AcceptSocketPackets(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = 0;
try
{
//blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch (Exception ex)
{
//a socket error has occured
Log(ex.Message);
break;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
Log("Client on " + tcpClient.Client.RemoteEndPoint + " has disconnected from the server");
break;
}
//message has successfully been received
UTF8Encoding encoder = new UTF8Encoding();
bufferincmessage = encoder.GetString(message, 0, bytesRead);
Log("Client from " + tcpClient.Client.RemoteEndPoint + ": " + bufferincmessage);
string stringToSend = "You sent me: " + bufferincmessage;
byte[] messageToSend = new byte[stringToSend.Length];
messageToSend = encoder.GetBytes(stringToSend);
clientStream.Write(messageToSend, 0, messageToSend.Length);
}
}
public void SocketAcceptCallback(IAsyncResult result)
{
TcpClient newClient = server.EndAcceptTcpClient(result);
Log("Accepted client on " + newClient.Client.RemoteEndPoint);
clientThreads.Add(new Thread(new ParameterizedThreadStart(AcceptSocketPackets)));
clientThreads[clientThreads.Count - 1].Start(newClient);
server.BeginAcceptTcpClient(SocketAcceptCallback, server);
}
private void Form1_Load(object sender, EventArgs e)
{
MainThread = Thread.CurrentThread;
clientThreads = new List<Thread>();
try
{
IPAddress localIP = null;
foreach (IPAddress addr in Dns.GetHostAddresses(Dns.GetHostName()))
{
if (addr.AddressFamily == AddressFamily.InterNetwork)
{
localIP = addr;
break;
}
}
localIP = IPAddress.Any;
// could also use this:
// server = new TcpListener(new IPEndPoint(IPAddress.Any, 1234));
server = new TcpListener(new IPEndPoint(localIP, 1234));
Log("Starting server on " + localIP + ":1234");
server.Start(6);
server.BeginAcceptTcpClient(SocketAcceptCallback, server);
Log("Started server on " + localIP + ":1234");
}
catch (Exception ex)
{
Log(ex.Message);
}
}
}
}
C++ is giving me problems like that. Try creating another project, paste the server code and build it as Release x86. If you change the build target and our problem is the same, windows firewall, even when turned off, won't allow the server or the client to run without any exception. If it doesn't work I might not know the answer.

Server socket in Android, Client sockect C# not sending until socket close

I have a socket server in Android and a client Socket in C#. The socket stablish connection properly but the information is not sended until the socket is close. Ot seems that the information is in buffer and it is not sended until the resources must be released.
The server code is:
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
try {
serverSocket = new ServerSocket(SocketServerPORT);
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
info.setText("I'm waiting here: "+ serverSocket.getLocalPort());
}
});
while (true) {
socket = serverSocket.accept();
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
String messageFromClient = "";
//If no message sent from client, this code will block the program
messageFromClient = dataInputStream.readLine();
count++;
message += "#" + count + " from " + socket.getInetAddress()+ ":" + socket.getPort() + "\n" + "Msg from client: " + messageFromClient + "\n";
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
msg.setText(message);
}
});
And the client code is:
IPAddress host = IPAddress.Parse("192.168.1.129");
IPEndPoint hostep = new IPEndPoint(host, 8080);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
sock.Connect(hostep);
//sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, true);
}
catch (SocketException ex) {
Console.WriteLine("Problem connecting to host");
Console.WriteLine(e.ToString());
sock.Close();
return;
}
try
{
string theMessageToSend = "Que mierda es esta";
byte[] msg = Encoding.Unicode.GetBytes(theMessageToSend + "$");
sock.Send(msg);
//sock.Send(Encoding.ASCII.GetBytes("testing %"));
} catch (SocketException ex) {
Console.WriteLine("Problem sending data");
Console.WriteLine( e.ToString());
sock.Close();
return;
}
sock.Close();
I can not reach the line messageFromClient = dataInputStream.readLine(); in the server side until the sock.Close(); is executed in the client side.
Many thanks in advance!

C# client communication Via UPD

I am looking for some help with communication between my server application and my client.The idea is that my client will listen for a UDP packet, read it and then execute a command based on what it reads.
My issue is that the server sends the packet however the client does nothing.
Here is a snippet of my code:
Client:
public void listen()
{
try
{
MessageBox.Show("");
UdpClient receivingUdpClient = new UdpClient(11000);
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 11000);
try
{
// Blocks until a message returns on this socket from a remote host.
Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
string[] split = returnData.Split(':');
if (split[0] == "SayHello")
{
MessageBox.show("Hello user","Hello");
}
//Note i have many commands but i shortened it to save room.
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
Server:
else if (radioButton4.Checked)
{
UdpClient udpClient = new UdpClient([IP_ADDRESS_HERE], 11000);
body = richTextBox1.Text;
title = textBox1.Text;
Command = "Message" + ":" + body + ":" + title + ":" + 4;
Byte[] sendBytes = Encoding.ASCII.GetBytes(Command);
try
{
udpClient.Send(sendBytes, sendBytes.Length);
}
catch (Exception)
{
Console.WriteLine(e.ToString());
}
}
Just wanted to see if you guys are able to find something I overlooked.
Check your Windows Firewall and verify it's not blocking your Client from opening port 11000.
Control Panel-> System and Security -> Windows Firewall

Problem with simple tcp\ip client-server

i'm trying to write simple tcp\ip client-server.
here is server code:
internal class Program
{
private const int _localPort = 7777;
private static void Main(string[] args)
{
TcpListener Listener;
Socket ClientSock;
string data;
byte[] cldata = new byte[1024];
Listener = new TcpListener(_localPort);
Listener.Start();
Console.WriteLine("Waiting connections [" + Convert.ToString(_localPort) + "]...");
try
{
ClientSock = Listener.AcceptSocket();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return;
}
int i = 0;
if (ClientSock.Connected)
{
while (true)
{
try
{
i = ClientSock.Receive(cldata);
}
catch
{
}
try
{
if (i > 0)
{
data = Encoding.ASCII.GetString(cldata).Trim();
ClientSock.Send(cldata);
}
}
catch
{
ClientSock.Close();
Listener.Stop();
Console.WriteLine(
"Server closing. Reason: client offline. Type EXIT to quit the application.");
}
}
}
}
}
And here is client code:
void Main()
{
string data; // Юзерская дата
byte[] remdata ={ };
TcpClient Client = new TcpClient();
string ip = "127.0.0.1";
int port = 7777;
Console.WriteLine("\r\nConnecting to server...");
try
{
Client.Connect(ip, port);
}
catch
{
Console.WriteLine("Cannot connect to remote host!");
return;
}
Console.Write("done\r\nTo end, type 'END'");
Socket Sock = Client.Client;
while (true)
{
Console.Write("\r\n>");
data = Console.ReadLine();
if (data == "END")
break;
Sock.Send(Encoding.ASCII.GetBytes(data));
Sock.Receive(remdata);
Console.Write("\r\n<" + Encoding.ASCII.GetString(remdata));
}
Sock.Close();
Client.Close();
}
When i'm sending to my server i cannt receive data back answer. Sock.Receive(remdata) returns nothing! Why?
You're trying to receive to an empty buffer. You should allocate the buffer with a sensible size, and then take note of the amount of data received:
byte[] buffer = new byte[1024];
...
int bytesReceived = socket.Receive(buffer);
string text = Encoding.ASCII.GetString(buffer, 0, bytesReceived);
(It's somewhat unconventional to use PascalCase for local variables, by the way. I'd also urge you not to just catch Exception blindly, and not to swallow exceptions without logging them.)

Categories