Fixing the cause from a Socket Exception in C# - c#

I'm creating a small server for multiple winform client connecting to it over the internet.
The following code works when it is set to the local address:
Server:
static void Main(string[] args)
{
TcpListener serverSocket = new TcpListener(9000);
TcpClient clientSocket = default(TcpClient);
int counter = 0;
serverSocket.Start();
Console.WriteLine("Chat Server Started ....");
counter = 0;
while ((true))
{
counter += 1;
clientSocket = serverSocket.AcceptTcpClient();
byte[] bytesFrom = new byte[10025];
string dataFromClient = null;
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
clientsList.Add(dataFromClient, clientSocket);
broadcast(dataFromClient + " Joined ", dataFromClient, false);
Console.WriteLine(dataFromClient + " Joined chat room ");
handleClinet client = new handleClinet();
client.startClient(clientSocket, dataFromClient, clientsList);
}
clientSocket.Close();
serverSocket.Stop();
Console.WriteLine("exit");
Console.ReadLine();
}
Winform Client:
public partial class Form1 : Form
{
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
NetworkStream serverStream = default(NetworkStream);
string readData = null;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
readData = "Conected to Chat Server ...";
msg();
clientSocket.Connect("127.0.0.1", 9000);
serverStream = clientSocket.GetStream();
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textBox3.Text + "$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
Thread ctThread = new Thread(getMessage);
ctThread.Start();
}
}
Those piece of code works fine talking to each other over the network.
But when I decide to change this line of code
clientSocket.Connect("127.0.0.1", 9000);
to
clientSocket.Connect("81.62.126.41", 9000);
for my ip address it gives me the following SocketException:
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
So some things I have tried. Port forwarding port 9000 because I am behind my router. Creating inbound and outbound rules for port 9000. And I have gone to http://www.canyouseeme.org/ while my server is running and the website can in fact see my service.
Anyone know what I can do to resolve this issue?
Here's a pic of netstat when the server is running. Thought it might be helpful.

I have had similar issue.
If you change only one string in your code and it stops working double-check the tools you're using. Some internal proxys could allow/disallow you to communicate with internal (127.0.0.1) or external ip.
Check the same URL in your browser 127.0.0.1:9000 and 81.62.126.41:9000. If it doesn't open for the second case then issue in your firewall or setting up your server to be able for external access, not in your code.
Your exception means that something wrong with your server: you could try open http://81.62.12.32/ and open http://81.62.126.41:9000/ and you will see two different errors.
Conclusion: Issue is not in your code. It's in your web server settings or in firewall set up.

Related

Tcp connection fails on LAN

I am trying to send a message from my laptop to my desktop over the LAN.
I have written a Tcp server that listens for a connection on a port, and a client that tries to connect to it and send a simple string as a message.
Server:
void Listen()
{
listener = new TcpListener(IPAddress.Any, port);
listener.Start();
while (true)
{
Debug.Log($"listening to {listener.LocalEndpoint}...");
var socket = listener.AcceptSocket();
Debug.Log("connected!");
var bytes = new byte[100];
int k = socket.Receive(bytes);
var data = Encoding.ASCII.GetString(bytes, 0, k);
Debug.Log(data);
socket.Send(new byte[] {1});
Debug.Log("responded");
socket.Close();
Debug.Log("closed connection");
}
}
Client:
public void Send()
{
client = new TcpClient();
Debug.Log("connecting...");
client.Connect("192.168.0.12", port);
Debug.Log("connected!");
var data = Encoding.ASCII.GetBytes("Hello!");
var stream = client.GetStream();
Debug.Log("sending data");
stream.Write(data, 0, data.Length);
Debug.Log("data sent! waiting for response...");
var reply = new byte[100];
stream.Read(reply,0,100);
Debug.Log("received response");
client.Close();
}
They communicate correctly when they are both on the same machine, but the client never connects to the server when I am running it on a different machine.
I have a rule in my firewall that allows an incoming connection through the port I have specified.
I have tried it with both computer's firewalls off and the connection still doesn't go through.
Any help would be greatly appreciated.

Could not send second message over TCP/IP

I am trying to send message over TCP/IP in c# application using TCPClient and TCPListner classes
Following is my code which i got from codeproject site.
Client code written over btn click
try
{
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("Connecting.....");
tcpclnt.Connect("192.168.0.102", 8001);
// use the ipaddress as in the server program
Console.WriteLine("Connected");
//Console.Write("Enter the string to be transmitted : ");
String str = textBox1.Text;
Stream stm = tcpclnt.GetStream();
ASCIIEncoding asen = new ASCIIEncoding();
byte[] ba = asen.GetBytes(str);
Console.WriteLine("Transmitting.....");
stm.Write(ba, 0, ba.Length);
byte[] bb = new byte[100];
int k = stm.Read(bb, 0, 100);
for (int i = 0; i < k; i++)
Console.Write(Convert.ToChar(bb[i]));
tcpclnt.Close();
}
catch (Exception ex)
{
Console.WriteLine("Error..... " + ex.Message);
}
Server code written on form_load
try
{
IPAddress ipAd = IPAddress.Parse("192.168.0.102");
// use local m/c IP address, and
// use the same in the client
/* Initializes the Listener */
TcpListener myList = new TcpListener(ipAd, 8001);
/* Start Listeneting at the specified port */
myList.Start();
Console.WriteLine("The server is running at port 8001...");
Console.WriteLine("The local End point is :" +
myList.LocalEndpoint);
Console.WriteLine("Waiting for a connection.....");
Socket s = myList.AcceptSocket();
Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
byte[] b = new byte[100];
int k = s.Receive(b);
Console.WriteLine("Recieved...");
string str = string.Empty;
for (int i = 0; i < k; i++)
{
Console.Write(Convert.ToChar(b[i]));
str = str + Convert.ToChar(b[i]);
}
label1.Text = str;
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes("The string was recieved by the server."));
Console.WriteLine("\nSent Acknowledgement");
/* clean up */
s.Close();
// myList.Stop();
}
Here on client, i m sending string written in textbox over tcp and it well recieved by server.
But when i trying to send another string, it fails without any exception and client application hangs for infinite time.
What is wrong here ?
Server should always be in listening mode, i.e the server code should be in while loop such that it can accept clients continuously. Your server will accept one client and then close itself. Therefore, if you click client's button, a new client tries to connect to server, but now the server won't be available.
Looking at the code you provided, the server only attempts to read 1 message from the client, so needs to be put in a loop to read the multiple incoming messages from the client, process the message and send response and then get more messages.
Note also that the server currently expects only one client to ever connect, processes that client and then closes.
The client is set up basically the same in the example, so you cant modify how one works without also modifying the other.

C# tcp socket (networkstream.read won't work with 8.1)

I've got a program that runs a tcp socket. It runs fine on anything below windows 8.1. I've already turned off my firewall and have set everything to allow this connection.
1.First the server does run on windows 8.1
2.The client socket does connect.
3.The client sends a string "login", to trigger the initial interaction.
-that string does get sent.
4.The connection fails when the server setup the networkstream.read();
-I'm not seeing anything in debugger, and again it works fine on other
-systems
here is how the I setup the server to listen. It's pretty traditional.
//LISTENS TO CLIENT
public String listen() {
byte[] bytesFrom = new byte[10025];
string dataFromClient = null;
NetworkStream networkStream = this.clientSocket.GetStream();//get client input
This is the line that fails{
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);//read client info } -end fail
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);//pass client input to String
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));//parse to end
//MessageBox.Show("data:" + dataFromClient);
networkStream.Flush();
// networkStream.Close();
MessageBox.Show("data:" + dataFromClient);
return dataFromClient;
}
create the buffer with clientSocket.ReceiveBufferSize so change:
byte[] bytesFrom = new byte[10025];
into:
byte[] bytesFrom = new byte[clientSocket.ReceiveBufferSize];
end get the buffersize from this array:
networkStream.Read(bytesFrom, 0, bytesFrom.Length);

Client_Server two .cs in one project issue

I have to get started with Client Server Communication for my application. To get started, I want to connect to local host.
Here's the code:
Server
public class serv
{
public static void Main()
{
try
{
IPAddress ipAd = IPAddress.Parse("127.0.0.1"); //use local m/c IP address, and use the same in the client
/* Initializes the Listener */
TcpListener myList=new TcpListener(ipAd,1025);
/* Start Listeneting at the specified port */
myList.Start();
Console.WriteLine("The server is running at port 1025...");
Console.WriteLine("The local End point is :" + myList.LocalEndpoint );
Console.WriteLine("Waiting for a connection.....");
Socket s=myList.AcceptSocket();
Console.WriteLine("Connection accepted from "+s.RemoteEndPoint);
byte[] b=new byte[100];
int k=s.Receive(b);
Console.WriteLine("Recieved...");
for (int i=0;i<k;i++)
Console.Write(Convert.ToChar(b[i]));
ASCIIEncoding asen=new ASCIIEncoding();
s.Send(asen.GetBytes("The string was recieved by the server."));
Console.WriteLine("\nSent Acknowledgement");
/* clean up */
s.Close();
myList.Stop();
Console.ReadKey();
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
}
}
Client
public class clnt
{
public static void Main()
{
try
{
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("Connecting.....");
tcpclnt.Connect("127.0.0.1",1025); // use the ipaddress as in the server program
Console.WriteLine("Connected");
Console.Write("Enter the string to be transmitted : ");
String str=Console.ReadLine();
Stream stm = tcpclnt.GetStream();
ASCIIEncoding asen= new ASCIIEncoding();
byte[] ba=asen.GetBytes(str);
Console.WriteLine("Transmitting.....");
stm.Write(ba,0,ba.Length);
byte[] bb=new byte[100];
int k=stm.Read(bb,0,100);
for (int i=0;i<k;i++)
Console.Write(Convert.ToChar(bb[i]));
tcpclnt.Close();
Console.ReadKey();
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
}
}
The Project has two Main() functions. So,to avoid conflict i set serv.cs as StartupObject but resulted in no-access to client's console window to send message.
1).How to use /run such programs on local host?
I actually needed a good starting point for using Sockets but most of the apps available on net are either quite obsolete or more advanced.I already had worked on Sockets using Linux but new to this environment.
2).Any good example other than this?
I have already googled up alot but SO is my last hope!.The projects on CodeProject are using UI and a simple Console app is needed for startup.
More than your code is not necessary.
Do you start both projects?
You have to start the server first, and then the client, so the client can connect to the waiting server.

WebApplication communication with a Windows Application via Socket

I have a problem on the Socket communication between a computer and the server. What happens is that I establish communication via socket only if I click on a particular button. In the first communication, everything happens perfectly. If I click again, the code is not executed. I put a breakpoint to see what is happening, and saw that occurs the following error when I try to connect to the server
Cannot access a disposed object. Object name: 'System.Net.Sockets.TcpClient'.
So, to work again, I close the client app and open again, and then works normally.
What I Want
I have a web application that has to work just on FireFox. I have a printer that I need to access him through DLL, so I made a client app that conects with this Web Application via Socket. I pass some parameter via stream and recover these parameter in client app and then print.
In my Web Application Code
public void btnImprimeBematech_Venda()
{
Utilidade.QuebraToken tk = new Utilidade.QuebraToken();
int Credenciada = Convert.ToInt32(tk.CarregaToken(1, HttpContext.Current.Request.Cookies["token"].Value));
TcpListener serverSocket = new TcpListener(8852);
int requestCount = 0;
TcpClient clientSocket = default(TcpClient);
serverSocket.Start();
while (true)
{
clientSocket = serverSocket.AcceptTcpClient();
requestCount = 0;
while (clientSocket.Connected == true)
{
try
{
requestCount = requestCount + 1;
NetworkStream networkStream = clientSocket.GetStream();
string serverResponse = Request.QueryString["id"].ToString() + ";" + Credenciada.ToString() + ".";
Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();
}
catch (Exception ex)
{
}
}
}
clientSocket.Close();
serverSocket.Stop();
}
I pass via stream a string, and recover in the client app.
Client app Code
`System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();`
private void Form1_Load(object sender, EventArgs e)
{
clientSocket.Connect("server_ip", 8852);
this.imprimir();
}
private void button3_click(object sender, EventArgs e)
{
if (clientSocket.Connected == false)
clientSocket.Connect("server_ip", 8852);
this.imprimir();
}
protected void imprimir()
{
NetworkStream serverStream = clientSocket.GetStream();
byte[] inStream = new byte[10025];
serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize);
string returndata = System.Text.Encoding.ASCII.GetString(inStream);
int ponto = returndata.IndexOf('.');
returndata = returndata.Substring(0, ponto);
string[] quebraretorno = returndata.Split(';');
ServiceReference1.bematechSoapClient bema = new ServiceReference1.bematechSoapClient();
string r = bema.InformacoesImovelBematech(quebraretorno[0], quebraretorno[1]);
int retorno = -1;
retorno = IniciaPorta("COM7");
if (retorno == 1)
{
ConfiguraModeloImpressora(7);
BematechTX(r);
AcionaGuilhotina(1);
FechaPorta();
}
clientSocket.Close();
}
I need that everytime that my user click on a specific button on my Web Application, call my btnImprimeBematech_Venda() and then talk to my Client App to print. Nowadays I need to close the Client App and open again everytime that my user click on my button to print.
I don't know so much about Thread but maybe I need to use that. I don't know.
Someone can help me ?
I think your problem is the Close() call at the end of your client app. Close will release all resources associated with the socket which explains your dispose exception. Try using Shutdown followed by Disconnect(true) which should allow your socket to be reused. See msdn docs here.
Alternatively you could keep the close, and create a new socket every time you connect.

Categories