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.
Related
There are two C# projects: one project is for the client, the other one is for the server. First step is to run the server , then to choose a target folder, after that to run the client project, to choose some text.txt to send to the server's target folder.
Only client can send files to the server
Demo:
1.choosing file target 2.client sends
+------------+
| tar folder | <---------------- text.txt
+------------+
My problem: there isn't compile errors or syntax errors in both projects, the only problem is that the server doesn't receives the .txt file.
Client:
First I designed a form for the client such as:
And placed an OpenFileDialog from the ToolBox-> Dialogs-> OpenFileDialog control.
Full code:
namespace SFileTransfer
{
public partial class Form1 : Form
{
string n;
byte[] b1;
OpenFileDialog op;
private void button1_Click(object sender, EventArgs e) //browse btn
{
op = new OpenFileDialog();
if (op.ShowDialog() == DialogResult.OK)
{
string t = textBox1.Text;
t = op.FileName;
FileInfo fi = new FileInfo(textBox1.Text = op.FileName);
n = fi.Name + "." + fi.Length;
TcpClient client = new TcpClient("127.0.0.1", 8100);//"127.0.0.1", 5055
StreamWriter sw = new StreamWriter(client.GetStream());
sw.WriteLine(n);
sw.Flush();
// label2.Text = "File Transferred....";
}
}
private void button2_Click(object sender, EventArgs e) //send btn
{
TcpClient client = new TcpClient("127.0.0.1", 8100);//5050
Stream s = client.GetStream();
b1 = File.ReadAllBytes(op.FileName);
s.Write(b1, 0, b1.Length);
client.Close();
// label2.Text = "File Transferred....";
}
}
}
Server:
Created and designed a Form for Server like:
Then Placed a folderBrowserDialog from the ToolBox->Dialogs-> folderBrowserDialog.
Full code:
namespace SFileTransferServer
{
public partial class Form1 : Form
{
string rd;
byte[] b1;
string v;
int m=1;
TcpListener list;
TcpClient client;
Int32 port = 8100;//5050
Int32 port1 = 8100;//5055
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
private void button1_Click(object sender, EventArgs e) //browse button
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = folderBrowserDialog1.SelectedPath;
list = new TcpListener(localAddr, port1);
list.Start();
client = list.AcceptTcpClient();
MessageBox.Show("ggggggg" + m.ToString());
Stream s = client.GetStream();
b1 = new byte[m];
s.Read(b1, 0, b1.Length);
MessageBox.Show(textBox1.Text);
File.WriteAllBytes(textBox1.Text+ "\\" + rd.Substring(0, rd.LastIndexOf('.')), b1);
list.Stop();
client.Close();
label1.Text = "File Received......";
}
}
private void Form2_Load(object sender, EventArgs e)
{
TcpListener list = new TcpListener(localAddr, port);
list.Start();
TcpClient client = list.AcceptTcpClient();
MessageBox.Show("Client trying to connect");
StreamReader sr = new StreamReader(client.GetStream());
rd = sr.ReadLine();
v = rd.Substring(rd.LastIndexOf('.') + 1);
m = int.Parse(v);
list.Stop();
client.Close();
}
}
}
Based on this page
I'm assuming you are a new coder because I'm seeing a lot of inefficient code.
On the Client App: Don't redeclare the TcpClient, instead declare it in the global scope and just reuse it.
Then On the server side: Always use the correct datatype IF AT ALL possible
Int16 port = 8100;
//same as
int port = 8100;
Then on to the question: First you are only reading a single byte from the received data
int m=1;
byte[] b1 = new byte[m];
s.Read(b1, 0, b1.Length);
//Then if you know the length of the byte, why do the computation of b1.Length, just use
s.Read(b1, 0, 1);
I see now you are also opeing the connection on the Load event. But that variable is not in the global scope so you are essentially creating a variable in the Load event then after the Load event finishes, sending it to the garbage collection and then declaring a variable with the same name in the button click event.
So try declaring the TcpListener object in the global scope then assign it in the load event and start listening.
Now the AcceptTcpClient() method is a blocking method so it will block your thead until it receives a connection attempt at which point it will return the client object. So try to use this instead:
https://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.accepttcpclient(v=vs.110).aspx
using System.Threading;
TcpClient client;
TcpListener server = new TcpListener("127.0.0.1",8100)
Thread incoming_connection = new Thread(ic);
incoming_connection.Start();
private void ic() {
client = server.AcceptTcpClient();
Stream s = client.GetStream();
//And then all the other code
}
Or you can use the Pending method as suggested by MSDN (on the ref page).
EDIT: using threading like this is 'not safe', so if you don't understand threading go read up on it first, this post doesn't cover how to use multi-threading.
I have this code that seems to stop working at Socket client = listener.AcceptSocket();
This code works fine in a console app but when I try to use it in a windows forms app it doesn't start / the windows doesn't show up
Here is my code:
public Form1()
{
InitializeComponent();
Listen();
}
public void Listen()
{
try
{
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
Console.WriteLine("Starting TCP listener...");
TcpListener listener = new TcpListener(ipAddress, 1302);
listener.Start();
while (true)
{
Console.WriteLine("Server is listening on " + listener.LocalEndpoint);
Console.WriteLine("Waiting for a connection...");
Socket client = listener.AcceptSocket(); // <----- PROBLEM
Console.WriteLine("Connection accepted.");
Console.WriteLine("Reading data...");
byte[] data = new byte[100];
int size = client.Receive(data);
Console.WriteLine("Recieved data: ");
for (int i = 0; i < size; i++)
Console.Write(Convert.ToChar(data[i]));
Console.WriteLine();
client.Close();
}
listener.Stop();
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.StackTrace);
Console.ReadLine();
}
}
private void button1_Click(object sender, EventArgs e)
{
if (richTextBox1.Text != "")
{
textToSend = richTextBox1.Text;
run = true;
}
else
{
MessageBox.Show("Box Cant Be Empty");
run = false;
}
if (run)
{
try
{
TCPclient = new TcpClient(SERVER_IP, PORT_NO);
nwStream = TCPclient.GetStream();
}
catch
{
}
byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(textToSend);
//---send the text---
MessageBox.Show("Sending : " + textToSend);
nwStream.Write(bytesToSend, 0, bytesToSend.Length);
}
}
The console will continue to output even when the code that is running is busy. It is painted outside of your application.
The windows form you are using needs the main application thread to be available for it to update and paint the form. You should look up the async / await pattern and learn to use it for blocking IO calls. The topic is too big to give you a simple quick answer, but you can find some information on async / await here: https://msdn.microsoft.com/library/hh191443(vs.110).aspx though there may be better articles to be found with some googlefu.
Some additional information can be found here about UI responsiveness:
https://msdn.microsoft.com/en-us/library/windows/desktop/dd744765(v=vs.85).aspx
Socket client = listener.AcceptSocket(); is waiting for an incoming packet. Unless and until it receives one, WinForm UI won't show up, as you are calling Listen(); in the form constructor, thus blocking the Main Thread(UI).
Run Listen(); in a separate thread.
I've been watching the following pair of videos on how to create a TCP/IP connection : Server and Client
What I need to do is create a game (flipcard) in which I send only 2 coordinates for a matrix. Nothing more. Or less.
(the code will follow)
From what I've observed, he closes and reopens the connection, everytime he send a message. It's working. But what do I modify in the code to keep the connection open and detect when a message arrived ?
All my google-searches brought me to these 2 methods:
I have had luck using the socket object directly (rather than the TCP client). (But I do not want to use sockets)
Also uses sockets
When I click to start the server
private void bStartServer_Click(object sender, EventArgs e)
{
Thread tcpServerRunThread = new Thread(new ThreadStart(TCPServerRun));
tcpServerRunThread.Start();
}
Server Runs and waits for a connection
private void TCPServerRun()
{
TcpListener tcpListener = new TcpListener(IPAddress.Any, 2016);
tcpListener.Start();
updateUI("Listening");
while (true)
{
TcpClient client = tcpListener.AcceptTcpClient();
updateUI("Connected");
Thread tcpHandlerThread = new Thread(new ParameterizedThreadStart(tcpHandler));
tcpHandlerThread.Start(client);
}
}
I handle my message
private void tcpHandler(object client)
{
TcpListener tcpListener = new TcpListener(IPAddress.Any, 5004);
TcpClient mClient = (TcpClient)client;
NetworkStream stream = mClient.GetStream();
byte[] message = new byte[1024];
stream.Read(message,0, message.Length);
updateUI("New message = " + Encoding.ASCII.GetString(message));
stream.Close();
mClient.Close();
}
NOTE: updateUI is a function made by him to update a listbox item
Client side - almost like the server side
`private void button1_Click(object sender, EventArgs e)
{
Thread mThread = new Thread(new ThreadStart(ConnectAsClient));
mThread.Start();
}
private void ConnectAsClient()
{
// aici putem inlocui cu adresa de IP dorita
//client.Connect(IPAddress.Parse(textBox.Text), 5004);
client = new TcpClient();
//client.Connect(IPAddress.Parse("127.0.0.1"), 2016); // for when I'm not connected to network
client.Connect(IPAddress.Parse("my_ip_here"), 2016); // for when I am connected to the network
updateUI("connected");
NetworkStream stream = client.GetStream();
string s = "Hello world!";
byte[] message = Encoding.ASCII.GetBytes(s);
stream.Write(message, 0, message.Length);
this.updateUI("Message sent!");
stream.Close();
// client.Close();
}`
If I'm not wrong, everytime he connects again, he creates a new connection, and not open the old one, right?
(It's my first time using TCP/IP, learning on my own, so I'd rather not use sockets, if possible)
-----------------------------------------------------------------------
Full link to my code (slighty modified from the videos provided at the beginning):
TCPClient
TCPServer
You are reconnecting every time you send the message. Use two different methods for this; one for connecting to the server and then another one for actually sending the message. Like so:
TcpClient client;
private void ConnectAsClient()
{
//client.Connect(IPAddress.Parse(textBox.Text), 5004);
client = new TcpClient();
//client.Connect(IPAddress.Parse("127.0.0.1"), 2016);
client.Connect(IPAddress.Parse("my_ip_here"), 2016);
updateUI("connected");
}
void SendMessage()
{
NetworkStream stream = client.GetStream();
string s = "Hello world!";
byte[] message = Encoding.ASCII.GetBytes(s);
stream.Write(message, 0, message.Length);
this.updateUI("Message sent!");
}
So my server and chat client are made from 2 different C# TCP tutorials.You may recognize 1 if not both of them and I have made my own modifications to them to fit my own style. When I tried both they worked perfectly fine with 0 loss, but my version has exactly a 50% loss rate.
For instance:
1. A client connects: Data received
2. A client sends text: No Data
3. A client sends text: Data received
4. A client sends text: No Data
The server code is as follows:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Net;
namespace WindowsFormsApplication2
{
class Server
{
private TcpListener tcpListener;
private Thread listenThread;
public Hashtable clientsList = new Hashtable();
private System.Windows.Forms.TextBox output;
private delegate void ObjectDelegate(String text);
private ObjectDelegate del;
public Server(System.Windows.Forms.TextBox setOut)
{
this.tcpListener = new TcpListener(IPAddress.Any, 8888);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.IsBackground = true;
this.listenThread.Start();
output = setOut;
del = new ObjectDelegate(outputTextToServer);
}
private void ListenForClients()
{
this.tcpListener.Start();
while (true)
{
//blocks until a client has connected to the server
TcpClient client = this.tcpListener.AcceptTcpClient();
//create a thread to handle communication
//with connected client
addClient(client);
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.IsBackground = true;
clientThread.Start(client);
}
}
private void HandleClientComm(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
{
//a socket error has occured
break;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
break;
}
//message has successfully been received
String text = getData(clientStream);
del.Invoke(text); //Used for Cross Threading & sending text to server output
//if filter(text)
sendMessage(tcpClient);
//System.Diagnostics.Debug.WriteLine(text); //Spit it out in the console
}
tcpClient.Close();
}
private void outputTextToServer(String text)
{
if (output.InvokeRequired)
{
// we then create the delegate again
// if you've made it global then you won't need to do this
ObjectDelegate method = new ObjectDelegate(outputTextToServer);
// we then simply invoke it and return
output.Invoke(method, text);
return;
}
output.AppendText(Environment.NewLine + " >> " + text);
}
private String getData(NetworkStream stream)
{
int newData;
byte[] message = new byte[4096];
ASCIIEncoding encoder = new ASCIIEncoding();
newData = stream.Read(message, 0, 4096);
String text = encoder.GetString(message, 0, newData); //Translate it into text
text = text.Substring(0, text.IndexOf("$")); //Here comes the money
return text;
}
private void addClient(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
String dataFromClient = getData(clientStream);
if (clientsList.Contains(dataFromClient))
{
Console.WriteLine(dataFromClient + " Tried to join chat room, but " + dataFromClient + " is already in use");
//broadcast("A doppleganger of " + dataFromClient + " has attempted to join!", dataFromClient, false);
}
else
{
clientsList.Add(dataFromClient, tcpClient);
//broadcast(dataFromClient + " Joined ", dataFromClient, false);
del.Invoke(dataFromClient + " Joined chat room ");
//handleClinet client = new handleClinet();
//client.startClient(clientSocket, dataFromClient, clientsList);
}
}
private Boolean connectionAlive(NetworkStream stream)
{
byte[] message = new byte[4096];
int bytesRead = 0;
try
{
//blocks until a client sends a message
bytesRead = stream.Read(message, 0, 4096);
}
catch
{
//a socket error has occured
return false;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
//clientsList.Remove
return false;
}
return true;
}
private void sendMessage(TcpClient client)
{
NetworkStream clientStream = client.GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes("Hello Client!");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
}
}
And here's my client code
using System;
using System.Windows.Forms;
using System.Text;
using System.Net.Sockets;
using System.Threading;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public delegate void newDelegate();
public newDelegate myDelegate;
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)
{
newMsg();
}
private void newMsg()
{
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textBox2.Text + "$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
textBox2.Text = "";
}
private void button2_Click(object sender, EventArgs e)
{
readData = "Connecting to Chat Server ...";
msg();
clientSocket.Connect(txtIP.Text, int.Parse(txtPort.Text));
serverStream = clientSocket.GetStream();
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(txtName.Text + "$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
myDelegate = new newDelegate(disconnect);
Thread ctThread = new Thread(getMessage);
ctThread.IsBackground = true;
ctThread.Start();
button2.Enabled = false;
}
private void getMessage()
{
while (true)
{
serverStream = clientSocket.GetStream();
int buffSize = 0;
byte[] inStream = new byte[clientSocket.ReceiveBufferSize];
buffSize = clientSocket.ReceiveBufferSize;
try
{
serverStream.Read(inStream, 0, buffSize);
string returndata = System.Text.Encoding.ASCII.GetString(inStream);
readData = "" + returndata;
msg();
}
catch
{
Invoke(myDelegate);
return;
}
}
}
private void disconnect()
{
button2.Enabled = true;
}
private void msg()
{
if (this.InvokeRequired)
this.Invoke(new MethodInvoker(msg));
else
textBox1.AppendText(Environment.NewLine + " >> " + readData);
//textBox1.Text = textBox1.Text + Environment.NewLine + " >> " + readData;
}
private void textBox2_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
newMsg();
}
}
private void cmdHost_Click(object sender, EventArgs e)
{
Server serv = new Server(txtLog);
}
}
}
This code is obviously a work in progress and sorry in advance for messiness. Any other suggestions to the code are also welcome.
Okay, this is starting to get a bit long.
There's multiple errors in your code. Starting with the server code:
As Damien noted, you're trying to read each "message" twice - first in HandleClientComm, then again in getData. The stream no longer has the original data, so you're just throwing one of the reads away completely (thus the suspicious 50% "packet" loss)
Later, in getData, you discard all the data in the stream after the first $. While this is obviously an attempt at handling message framing (since TCP is a stream-based protocol, not a message-based protocol), it's a silly one - you're throwing the data away. The reason this didn't show in your testing is that 1) Windows treats local TCP very differently from remote TCP, 2) You'd need to be actually able to send two messages fast enough to make them "blend" together in the stream. That means either sending two messages in about 200ms (default TCP buffering) or blocking on reads.
You keep Flushing the network stream. This doesn't actually do anything, and even if it did, you wouldn't want to do that.
connectionAlive reads from the shared socket - this is always a bad idea. Never have more than one reader - multiple readers don't work with stream-based protocols. It doesn't seem you're using it in your sample code, but beware of trying to.
The commented out clientList.Remove would of course be a cross-thread access of a shared field. If you want to do it like this, you'll have to ensure the concurrent access is safe - either by using ConcurrentDictionary instead of HashSet, or by locking around each write and read of clientList.
You're expecting to get the whole message in one Read. That may be fine for a simple chat client, but it's bad TCP anyway - you need to read until you find your message terminator. If I send a message big enough, your code will just drop dead on text.IndexOf("$").
There's a lot of "style" issues as well, although this isn't code review, so let me just list some: using ancient technology, synchronous sockets for the server, mixing multi-threaded code with GUI at will. This is mostly about maintainability and performance, though - not correctness.
Now, the client is a bit simpler:
Again, don't Flush the network stream.
Don't use background threads if you don't have to. Simply make sure to terminate the connections etc. properly.
Disconnect should actually disconnect. It's not that hard, just close the TcpClient.
What is readData = "" + returndata supposed to do? That's just silly.
You're ignoring the return value of Read. This means that you have no idea how many bytes of data you read - which means your returnData string actually contains the message followed by a few thousand \0 characters. The only reason you don't see them in output is because most of Windows uses \0 as the string terminator ("it made sense at the time"). .NET doesn't.
Again, the Read expects the whole message at once. Unlike the server, this isn't going to crash the client, but your code will behave differently (e.g. an extra \r\n >> even though it's not a separate message.
The style issues from the server also apply here.
As a side-note, I've recently made a simplified networking sample that handles a simple chat client-server system using more modern technologies - using await-based asynchronous I/O instead of multi-threading, for example. It's not production-ready code, but it should show the ideas and intent quite clearly (I also recommend having a look at the first sample, "HTTP-like TCP communication"). You can find the full source code here - Networking Part 2.
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.