SocketException when connecting to server - c#

I am running both client and server on the same machine.
Does any 1 know the error stated above?
server
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net.Sockets;
using System.IO;
using System.Net;
namespace Server
{
public partial class Server : Form
{
private Socket connection;
private Thread readThread;
private NetworkStream socketStream;
private BinaryWriter writer;
private BinaryReader reader;
//default constructor
public Server()
{
InitializeComponent();
//create a new thread from server
readThread = new Thread(new ThreadStart(RunServer));
readThread.Start();
}
protected void Server_Closing(object sender, CancelEventArgs e)
{
System.Environment.Exit(System.Environment.ExitCode);
}
//sends the text typed at the server to the client
protected void inputText_KeyDown(object sender, KeyEventArgs e)
{
// send the text to client
try
{
if (e.KeyCode == Keys.Enter && connection != null)
{
writer.Write("Server>>> " + inputText.Text);
displayText.Text +=
"\r\nSERVER>>> " + inputText.Text;
//if user at server enter terminate
//disconnect the connection to the client
if (inputText.Text == "TERMINATE")
connection.Close();
inputText.Clear();
}
}
catch (SocketException)
{
displayText.Text += "\nError writing object";
}
}//inputTextBox_KeyDown
// allow client to connect & display the text it sends
public void RunServer()
{
TcpListener listener;
int counter = 1;
//wait for a client connection & display the text client sends
try
{
//step 1: create TcpListener
IPAddress ipAddress = Dns.Resolve("localhost").AddressList[0];
TcpListener tcplistener = new TcpListener(ipAddress, 9000);
//step 2: TcpListener waits for connection request
tcplistener.Start();
//step 3: establish connection upon client request
while (true)
{
displayText.Text = "waiting for connection\r\n";
// accept incoming connection
connection = tcplistener.AcceptSocket();
//create NetworkStream object associated with socket
socketStream = new NetworkStream(connection);
//create objects for transferring data across stream
writer = new BinaryWriter(socketStream);
reader = new BinaryReader(socketStream);
displayText.Text += "Connection " + counter + " received.\r\n ";
//inform client connection was successful
writer.Write("SERVER>>> Connection successful");
inputText.ReadOnly = false;
string theReply = "";
// step 4: read string data sent from client
do
{
try
{
//read the string sent to the server
theReply = reader.ReadString();
// display the message
displayText.Text += "\r\n" + theReply;
}
// handle the exception if error reading data
catch (Exception)
{
break;
}
} while (theReply != "CLIENT>>> TERMINATE" && connection.Connected);
displayText.Text +=
"\r\nUser terminated connection";
// step 5: close connection
inputText.ReadOnly = true;
writer.Close();
reader.Close();
socketStream.Close();
connection.Close();
++counter;
}
} //end try
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}
}// end method runserver
}// end class server
client
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net.Sockets;
using System.IO;
using System.Net;
namespace Client
{
public partial class Client : Form
{
private NetworkStream output;
private BinaryWriter writer;
private BinaryReader reader;
private string message = "";
private Thread readThread;
//default constructor
public Client()
{
InitializeComponent();
readThread = new Thread(new ThreadStart(RunClient));
readThread.Start();
}
protected void Client_Closing(
object sender, CancelEventArgs e)
{
System.Environment.Exit(System.Environment.ExitCode);
}
//sends the text user typed to server
protected void inputText_KeyDown(
object sender, KeyEventArgs e)
{
try
{
if (e.KeyCode == Keys.Enter)
{
writer.Write("CLIENT>>> " + inputText.Text);
displayText.Text +=
"\r\nCLIENT>>> " + inputText.Text;
inputText.Clear();
}
}
catch (SocketException ioe)
{
displayText.Text += "\nError writing object";
}
}//end method inputText_KeyDown
//connect to server & display server-generated text
public void RunClient()
{
TcpClient client;
//instantiate TcpClient for sending data to server
try
{
displayText.Text += "Attempting connection\r\n";
//step1: create TcpClient for sending data to server
client = new TcpClient();
client.Connect("localhost", 9000);
//step2: get NetworkStream associated with TcpClient
output = client.GetStream();
//create objects for writing & reading across stream
writer = new BinaryWriter(output);
reader = new BinaryReader(output);
displayText.Text += "\r\nGot I/O streams\r\n";
inputText.ReadOnly = false;
//loop until server terminate
do
{
//step3: processing phase
try
{
//read from server
message = reader.ReadString();
displayText.Text += "\r\n" + message;
}
//handle exception if error in reading server data
catch (Exception)
{
System.Environment.Exit(System.Environment.ExitCode);
}
} while (message != "SERVER>>> TERMINATE");
displayText.Text += "\r\nClosing connection.\r\n";
//step4: close connection
writer.Close();
reader.Close();
output.Close();
client.Close();
Application.Exit();
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}
}
}

It is probably your firewall acting up. Try connecting to something like www.google.com on TCP 80 just to see if you can actually connect.

Are you using a newer version of Windows? It's possible that you're only listening on IPv4, but "localhost" is resolving to an IPv6 address and it's not finding it. Try connecting to "127.0.0.1" instead of localhost and see if the result changes.

mk,
I'd tcplistener/tcpclient for simple applications . . .
TheEruditeTroglodyte

If you use that constructor with TCPListener then it will let the underlying service provider pick a network address, which probably won't be 'localhost'. You're probably listening on your LAN/WLAN card instead of localhost.
Take a look at the MSDN page for TCPListener, the sample there shows how to use a different constructor, look at the other constructors for more samples.
Here's one way:
IPAddress ipAddress = Dns.Resolve("localhost").AddressList[0];
TcpListener tcpListener = new TcpListener(ipAddress, 9000);

Related

Problem with sending and receiving in streams C# in textbox Windows Forms app

I managed to create a client server that communicate through forms.
I am able to display fist waiting and accepted messages.
My problem is when I'm writing to the stream and reading it on the other side the forms.
Here is where the sending and receiving happens on both programs:
Server-side code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Net;
using System.Diagnostics;
namespace serverApp
{
public partial class Form1 : Form
{
private static int connections = 0;
public Form1() { }
private void Form1_Load(object sender, EventArgs e)
{
}
private void CreateServer()
{
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
IPEndPoint localEP = new IPEndPoint(IPAddress.Any, 9050);
server.Bind(localEP);
server.Listen(10);
serverTxtbox.AppendText("waiting for a client");
BackgroundWorker worker1 = new BackgroundWorker();
worker1.RunWorkerAsync(handlingFunction(server));
}
public object handlingFunction(Socket server)
{
while (true)
{
try
{
Socket client = server.Accept();
NetworkStream ns = new NetworkStream(client);
StreamReader reader = new StreamReader(ns);
StreamWriter writer = new StreamWriter(ns);
connections++;
serverTxtbox.AppendText("New client accepted: active connections
${connections}");
writer.WriteLine("Welcome to my server");
writer.Flush();
string input;
while (true)
{
input = reader.ReadLine();
if (input.Length == 0 || input.ToLower() == "exit")
break;
serverTxtbox.AppendText(input);
writer.WriteLine(input);
writer.Flush();
} //end of while
ns.Close();
//client.Close();
//connections--;
Console.WriteLine("Client disconnected: {0} active connections",
connections);
}
catch (Exception)
{
connections--;
Console.WriteLine("Client disconnected: {0} active connections", connections);
} //end of catch block
} // end of HandleConnection function
private void serverTxtbox_TextChanged(object sender, EventArgs e)
{
serverTxtbox.Clear();
}
private void button1_Click(object sender, EventArgs e)
{
//start button
try
{
CreateServer();
}
catch (Exception)
{
serverTxtbox.AppendText("Connection failed ..");
}
//client.Close();
//server.Shutdown();
}
}
}
Client-side code:
using System;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;
namespace app
{
public partial class Form1 : Form
{
Socket client;
NetworkStream stream;
StreamReader reader;
StreamWriter writer;
public Form1()
{
InitializeComponent();
}
private void sendBtn_Click(object sender, EventArgs e)
{
// writing to the server
handlfun();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private object ConnectionToServer(Socket client, IPEndPoint remoteEP)
{
//client.Connect(remoteEP);
try
{
client.Connect(remoteEP);
clientTextbox.Text = "Enter Message for Server <Enter to Stop >: ";
}
catch (SocketException e)
{
clientTextbox.AppendText("Unable to connect to server. ");
// clientTextbox.AppendText("e");
}
return client;
// Client.Shutdown(SocketShutdown.Both);
// Client.Close();
}
private void connectbtn_Click(object sender, EventArgs e)
{
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
BackgroundWorker worker1 = new BackgroundWorker();
worker1.RunWorkerAsync(ConnectionToServer(client, remoteEP));
}
public void handlfun()
{
stream = new NetworkStream(client);
reader = new StreamReader(stream);
writer = new StreamWriter(stream);
String input = clientTextbox.Text;
writer.WriteLine(input);
//clientTextbox.Text = input;
// String input = reader.ReadLine();
writer.Flush();
String line = null;
while (true)
{
clientTextbox.Text = "Enter Message for Server <Enter to Stop >: ";
line = clientTextbox.Text;
writer.WriteLine(line);
writer.Flush();
if (line.Length != 0)
{
line = "Echo: " + reader.ReadLine();
clientTextbox.Text = line;
}
}
}
}
}

How can I make a server program keep running no matter what happens to a client?

Take a look at the following two programs:
//Server
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace MyServerProgram
{
class Program
{
static void Main(string[] args)
{
IPAddress ip = IPAddress.Parse("127.0.0.1");
int port = 2000;
TcpListener listener = new TcpListener(ip, port);
listener.Start();
TcpClient client = listener.AcceptTcpClient();
Console.WriteLine("Connected " + ((IPEndPoint)client.Client.RemoteEndPoint).Address);
NetworkStream netStream = client.GetStream();
BinaryReader br = new BinaryReader(netStream);
try
{
while (client.Client.Connected)
{
string str = br.ReadString();
Console.WriteLine(str);
}
}
catch (Exception ex)
{
var inner = ex.InnerException as SocketException;
if (inner != null && inner.SocketErrorCode == SocketError.ConnectionReset)
Console.WriteLine("Disconnected");
else
Console.WriteLine(ex.Message);
br.Close();
netStream.Close();
client.Close();
listener.Stop();
}
}
}
}
//Client
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace MyClientProgram
{
class Program
{
static void Main(string[] args)
{
int port = 2000;
TcpClient client = new TcpClient("localhost", port);
NetworkStream netStream = client.GetStream();
BinaryWriter br = new BinaryWriter(netStream);
try
{
int i=1;
while (client.Client.Connected)
{
br.Write(i.ToString());
br.Flush();
i++;
int milliseconds = 2000;
System.Threading.Thread.Sleep(milliseconds);
}
}
catch
{
br.Close();
netStream.Close();
client.Close();
}
}
}
}
The problem I am facing with the Server is, the Server program exits as soon as the client is closed.
I want the server program to keep running no matter what a client does or happens to it.
How can I do that?
Try putting a while loop around your AcceptTcpClient (and associated logic).
To paraphrase from your server code:
boolean keepRunning = true;
while (keepRunning) {
TcpClient client = listener.AcceptTcpClient();
Console.WriteLine("Connected ...") // and other stuff deleted.
// while client connected...
string str = br.ReadString();
// check to see if we should continue running.
keepRunning = ! "quit".equalsIgnoreCase(str);
// Other stuff
Note this is very insecure - any client regardless of where / who they are could terminate your server be sending a "quit" message to your server. In real life, you would probably require a more strict mechanism. Obviously with this mechanism, you will need your client to be able to generate the "quit" message text when you need it to do so.
Another method is to run the whole server in a Thread. Then in another thread, have a method that an operator could use to close the server (e.g. a menu selection in a Swing Application).
There are plenty of options you could choose from to "manage" the shutdown.
Also, as written, your code is single threaded. That is, it will wait for a client to connect, deal with that client and then exit (or if you apply the keepRunning while loop modification wait for the next client to connect). But, only one client can connect to this server at any one time.
To make it multi-threaded (can service multiple clients at one time), put the body of your server (the service code) into a Thread and invoke a new instance of the Thread to serve that client. After starting the service Thread, the main loop simply waits for the next client to connect.
Thus, your main loop will become something like this:
while (keepRunning) {
TcpClient client = listener.AcceptTcpClient();
Console.WriteLine("Connected ...") // and other stuff deleted.
ServiceThread st = new ServiceThread(client);
st.start ();
}
and the Service Thread will be something like:
public class ServiceThread extends Thread {
private TcpClient client;
public ServiceThread (TcpClient client) {
this.client = client;
}
#override
public void run() {
NetworkStream netStream = client.GetStream();
BinaryReader br = new BinaryReader(netStream);
try {
while (client.Client.Connected) {
// Stuff deleted for clarity
}
}
catch (Exception ex) {
// Exception handling stuff deleted for clarity.
}
}
}

connecting POP3 via http proxy using HigLabo

I'm using HigLabo to create an email client. Also I need to use an http proxy.
But authentication fails every time.
I found the base code here : .net pop3 over http proxy
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HigLabo.Net;
using HigLabo.Net.Pop3;
using System.Net.Sockets;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
static Pop3Client pop;
static Socket socket;
static void Main(string[] args)
{
String proxyAddr = "112.241.212.104"; //This seemed to be working
int proxyPort = 8585;
byte[] buffer = new byte[25];
pop = new Pop3Client("PopClient");
socket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
Console.WriteLine("Connecting to proxy...");
socket.Connect(proxyAddr, proxyPort);
Console.WriteLine("Connected to proxy");
Console.WriteLine("Sending Packets...");
socket.Send(Encoding.UTF8.GetBytes("CONNECT pop.mail.yahoo.com:995 HTTP/1.1<CR><LF>"));
socket.Send(Encoding.UTF8.GetBytes("<CR><LF>"));
Console.WriteLine("Packets sent");
Console.WriteLine("Waiting for response...");
socket.Receive(buffer);
Console.WriteLine("Packets received");
Console.WriteLine("Time Elapsed : " + timeElapsed + " seconds");
Console.WriteLine("Connectong POP to socket...");
if (pop.Connect(socket))
{
pop.Connect();
Console.WriteLine("Connection completed");
}
else
{
Console.WriteLine("Disconnected");
Disconnect();
return;
}
pop.Ssl = true;
pop.UserName = "EMAIL_ADDRESS";
pop.Password = "PASSWORD";
pop.ServerName = "pop.gmail.com";
pop.Port = 995;
Console.WriteLine("Authenticating...");
if (pop.Authenticate())
{
Console.WriteLine("Authentication completed"); //Never comes here
GetMail();
}
else
{
Console.WriteLine("Authentication failed"); //Always comes here
Disconnect();
}
}
private static void GetMail()
{
HigLabo.Mime.MailMessage msg = pop.GetMessage(1);
Console.WriteLine(msg.BodyText);
}
static void Disconnect()
{
Console.WriteLine("Disconnecting...");
pop.Close();
socket.Close();
Console.WriteLine("Disconnected");
}
}
}
I gave permission for the app also.
What is wrong here?
Are there any other/better/easy ways to do this? May be with a different library?
This is wrong: <CR><LF>.
What you want to use is \r\n in your strings.

UDP sending but not receiving

I'm working on creating a UDP socket to send and receive data through the PC and a radio terminal device connected to the PC. I can successfully send the data that I want to send, but when it comes to receiving data sent from the radio device to the PC nothing happens the code just stops at the " Byte[] receiveBytes = receivingUdpClient.Receive(ref ipep); " in the Receive function and nothing happens afterwords. The radio device has an IP address = 192.168.1.191 and Port number = 50000. I've also tried to receive through " Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint); " but still nothing the code also stops at this point and nothing happens afterwords. Below is the complete code that I have. Any help would be very appreciated, thanks in advance.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
namespace UDP_Socket
{
public partial class Form1 : Form
{
#region Importand Definitions
public UdpClient udpClient;
public String IPaddress;
public String PortNumber;
public IPEndPoint ipep;
#endregion
private void Form1_Load(object sender, EventArgs e)
{
Connect();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (udpClient.Client.Connected == true)
{
udpClient.Client.Close();
udpClient.Client.Dispose();
}
}
private void Add_Btn_Click(object sender, EventArgs e)
{
RadioCheck();
Receive();
}
void RadioCheck()
{
byte[] data = Encoding.ASCII.GetBytes("at");
udpClient.Send(data , data .Length);
}
void Connect()
{
IPaddress = "192.168.1.191";
PortNumber = "50000";
//Uses a remote endpoint to establish a socket connection.
udpClient = new UdpClient();
IPAddress ipAddress = IPAddress.Parse(IPaddress);
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, Convert.ToInt32(PortNumber));
ipep = ipEndPoint;
try
{
udpClient.Connect(ipEndPoint);
MessageBox.Show("Successfully connected to: " + ipep.ToString(), "Connection", MessageBoxButtons.OK);
}
catch (SocketException ex)
{
Console.WriteLine(ex.ToString());
MessageBox.Show("Problem connecting to: " + ipep.ToString(), "Connection", MessageBoxButtons.OK);
}
}
void Receive()
{
//Creates a UdpClient for reading incoming data.
UdpClient receivingUdpClient = new UdpClient(50000);
//Creates an IPEndPoint to record the IP Address and port number of the sender.
// The IPEndPoint will allow you to read datagrams sent from any source.
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
try
{
Byte[] receiveBytes = receivingUdpClient.Receive(ref ipep);//RemoteIpEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
Console.WriteLine("This is the message you received " +
returnData.ToString());
Console.WriteLine("This message was sent from " +
ipep.Address.ToString() +
" on their port number " +
ipep.Port.ToString()); //RemoteIpEndPoint
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}

Error in Working with Socket When Sending Object Frequently

I'm writing a program that can manage computers in a network environment.
I try to be a part of this program will assign the control of the remote client(Remote Desktop) . but my target is like teamviewer not RDC(RDP) .
i want make a service and put it into Client , that Service running every time (Automatic , Auto Start)
I use sending mouse and keyboard from server to client and screenshot of desktop of client will be transfer to server, the destination computer must control.
i write it by BackgroundWorker in loop ( in Complete_BW i put BW.RunWorkerAsync() )
i use socket and when i run program my server rise error after 1 or 2 times sent desktop image to server , error is in Socket.EndPoint ...
codes is here :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.IO;
namespace remServer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
bw.RunWorkerAsync();
}
public Image GetImage(byte[] byteArrayIn)
{
Image ret = null;
try
{
MemoryStream ms = new MemoryStream(byteArrayIn);
ret = Image.FromStream(ms);
}
catch { }
return ret;
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
FTServerCode f = new FTServerCode();
Byte[] getCap = f.StartServer();
img.Image = GetImage(getCap);
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
bw.RunWorkerAsync();
}
}
public class FTServerCode
{
IPEndPoint ipEnd;
Socket sock;
public FTServerCode()
{
try
{
ipEnd = new IPEndPoint(IPAddress.Any, 5656); // Error In this Line
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
sock.Bind(ipEnd);
}
catch { }
}
public Byte[] StartServer()
{
byte[] clientData = new byte[1024 * 5000];
try
{
sock.Listen(100);
Socket clientSock = sock.Accept();
int receivedBytesLen = clientSock.Receive(clientData);
clientSock.Close();
}
catch (Exception ex)
{
MessageBox.Show("File Receving error." + ex.Message);
}
return clientData;
}
}
}
if client code is Necessary tell me to put in here . tnx

Categories