Why isnt my second form loading on startup? Is it stuck? - c#

So I just want to make it clear that I am very new to Tcp / IP programming in C#. Also, I've changed the IP's in the question to not match the ones in my project due not not wanting to leak it.
When ever I start the project it should open 2 forms (Client & server)
but for some reason it only opens the Client winform application.
(I've changed the start method in the project settings to start both)
My best guess would be that its stuck on trying to start the TcpListener when ever I call it in the Form_Load event.
Why is this happening and how do I fix it?
Here is the server (the one that doesnt start)
using System;
using System.Windows.Forms;
using System.Net.Sockets;
using System.IO;
using System.Net;
namespace SimpleServer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string rd;
byte[] b1;
string v;
int m;
//TcpListener list;
Int32 port = 8080;
Int32 port1 = 8080;
IPAddress localAddr = IPAddress.Parse("192.168.0.1");
private void BrowseBtn_Click(object sender, EventArgs e)
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = folderBrowserDialog1.SelectedPath;
TcpListener list = new TcpListener(localAddr, port1);
//list = new TcpListener(port1);
list.Start();
TcpClient client = list.AcceptTcpClient();
Stream s = client.GetStream();
b1 = new byte[m];
s.Read(b1, 0, b1.Length);
File.WriteAllBytes(textBox1.Text + "\\" + rd.Substring(0, rd.LastIndexOf('.')), b1);
list.Stop();
client.Close();
statusLabel.Text = "File Received......";
}
}
private void Form1_Load(object sender, EventArgs e)
{
IPAddress localAddr = IPAddress.Parse("192.168.0.1"); //changed it from my main ip
TcpListener list = new TcpListener(localAddr, port);
//TcpListener list = new TcpListener(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();
}
}
}
And here is the client source 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;
namespace SimpleClient
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string n;
byte[] b1;
OpenFileDialog op;
private void browseButton_Click(object sender, EventArgs e)
{
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("22.232.23.22", 8080);
StreamWriter sw = new StreamWriter(client.GetStream());
sw.WriteLine(n);
sw.Flush();
statusLabel.Text = "File Transferred....";
}
}
private void sendBtn_Click(object sender, EventArgs e)
{
TcpClient client = new TcpClient("22.232.23.22", 8080);
Stream s = client.GetStream();
b1 = File.ReadAllBytes(op.FileName);
s.Write(b1, 0, b1.Length);
client.Close();
statusLabel.Text = "File Transferred2....";
}
}
}

You can only have one startup project in a solution... Right Click Project in Solution Explorer and choose "Set as Startup Project"
When you deploy the exe's you will have to start the server Exe either manually, by Scheduled Task or better yet make the Server Exe run as a Service.
Another way you could do it is System.Diagnostic.Process.Start("..\bin\Debug\SimpleServer.exe");

The issue was that it couldnt connect because the ip adresses didnt match in the client and the server. Both had to be a IPV4 adress.

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

c# TCP IP client and server no respond error

i have a simple TCP/IP client and server that does not work:
i want to use it to transfer data between some clients and a server
enter image description here
enter image description here
on server side i have:
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.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Collections;
namespace TCP_IP_Server
{
public partial class frmMain : Form
{
private ArrayList nSockets;
public frmMain()
{
InitializeComponent();
}
private void frmMain_Load(object sender, EventArgs e)
{
IPHostEntry IPhost = Dns.GetHostByName(Dns.GetHostName());
lblStatus.Text = "IP Address: " + IPhost.AddressList[0].ToString();
nSockets = new ArrayList();
Thread thdListner = new Thread(new ThreadStart(listnerThread));
}
public void listnerThread()
{
TcpListener tcpListener = new TcpListener(8080);
tcpListener.Start();
while(true)
{
Socket handlerSocket = tcpListener.AcceptSocket();
if(handlerSocket.Connected)
{
Control.CheckForIllegalCrossThreadCalls = false;
lbConnections.Items.Add(handlerSocket.RemoteEndPoint.ToString() + " Connected.");
lock (this)
{
nSockets.Add(handlerSocket);
}
ThreadStart thdstHandler = new ThreadStart(handlerThread);
Thread thdHnadler = new Thread(thdstHandler);
thdHnadler.Start();
}
}
}
public void handlerThread()
{
Socket handlerSocket = (Socket)nSockets[nSockets.Count - 1];
NetworkStream networkStream = new NetworkStream(handlerSocket);
int thisRead = 0;
int BlockSize = 1024;
byte[] dataByte = new byte[BlockSize];
lock (this)
{
Stream fileStream = File.OpenWrite(#"%userprofile%\desktop\SubmitedFile.txt");
while(true)
{
thisRead = networkStream.Read(dataByte, 0, BlockSize);
fileStream.Write(dataByte, 0, thisRead);
if (thisRead == 0)
break;
}
fileStream.Close();
}
lbConnections.Items.Add("File Written.");
handlerSocket = null;
}
}
}
and on Clinet side:
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.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace TCP_IP_Client
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
private void btnBrowse_Click(object sender, EventArgs e)
{
ofdBrowse.ShowDialog();
txtFile.Text = ofdBrowse.FileName;
}
private void btnSend_Click(object sender, EventArgs e)
{
Stream fileStream = File.OpenRead(txtFile.Text);
byte[] fileBuffer = new byte[fileStream.Length];
fileStream.Read(fileBuffer, 0, (int)fileStream.Length);
TcpClient tcp = new TcpClient(txtServer.Text, 8080);
NetworkStream networkStream = tcp.GetStream();
networkStream.Write(fileBuffer, 0, fileBuffer.GetLength(0));
networkStream.Close();
}
}
}
i am running the server on a VPS that hase statick IP adress and the client on my own pc, but after hiting send button an exception occures:
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 **.**.**.**:8080
1. Programmatic Issue
Don't forget to start the thread after creating
private void frmMain_Load(object sender, EventArgs e)
{
IPHostEntry IPhost = Dns.GetHostByName(Dns.GetHostName());
lblStatus.Text = "IP Address: " + IPhost.AddressList[0].ToString();
nSockets = new ArrayList();
Thread thdListner = new Thread(new ThreadStart(listnerThread));
thdListner.start();
}
2. Network Issue
Take the IP-address used by the code to host the server and Ping the address on the client.
If succeeded, check the firewall settings of the server, client (may temporarly switch of the firewall to check if this is the problem)
If you're using dns names execute an nslookup on the client

How to make server client autodiscover over a lan

I have two project "Server" and "Client" that communicate over a LAN,
this my server code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ServerClientProject
{
public partial class FormServer : Form
{
private static Int32 port;
private static string filePath;
TcpListener server = new TcpListener(IPAddress.Any, port);
public FormServer()
{
InitializeComponent();
}
private void FormServer_Load(object sender, EventArgs e)
{
File.WriteAllText("path.misc","");
File.WriteAllText("nama.misc","");
filePath = readPath();
label1.Text = filePath;
label2.Text = readNama();
label3.Text = IPAddressCheck();
label4.Text = UNCPathing.GetUNCPath(readPath());
label5.Text = GetFQDN();
bw.WorkerSupportsCancellation = true;
bw.WorkerReportsProgress = true;
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
if (bw.IsBusy != true)
{
bw.RunWorkerAsync();
}
}
private static string IPAddressCheck()
{
IPHostEntry IPAddr;
IPAddr = Dns.GetHostEntry(GetFQDN());
IPAddress ipString = null;
foreach (IPAddress ip in IPAddr.AddressList)
{
if (IPAddress.TryParse(ip.ToString(), out ipString) && ip.AddressFamily == AddressFamily.InterNetwork)
{
break;
}
}
return ipString.ToString();
}
public static string GetFQDN()
{
string domainName = IPGlobalProperties.GetIPGlobalProperties().DomainName;
string hostName = Dns.GetHostName();
if (!hostName.EndsWith(domainName)) // if hostname does not already include domain name
{
hostName += "." + domainName; // add the domain name part
}
return hostName; // return the fully qualified name
}
private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
lstProgress.Items.Add(e.UserState);
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
if ((worker.CancellationPending == true))
{
e.Cancel = true;
}
else
{
try
{
// Set the TcpListener on port 1333.
port = 1337;
//IPAddress localAddr = IPAddress.Parse("127.0.0.1");
TcpListener server = new TcpListener(IPAddress.Any, port);
//label2.Text = IPAddressToString(ip);
// Start listening for client requests.
server.Start();
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;
// Enter the listening loop.
while (true)
{
bw.ReportProgress(0, "Waiting for a connection... ");
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
bw.ReportProgress(0, "Connected!");
data = null;
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
int i;
// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
bw.ReportProgress(0, String.Format("Received: {0}", data));
if (data == "file")
{
// Process the data sent by the client.
data = String.Format("Request: {0}", data);
byte[] mssg = System.Text.Encoding.ASCII.GetBytes(label4.Text);
// Send back a response.
stream.Write(mssg, 0, mssg.Length);
bw.ReportProgress(0, String.Format("Sent: {0}", data));
bw.ReportProgress(0, String.Format("File path : {0}", label4.Text));
}
else if (data == "nama")
{
byte[] mssg = System.Text.Encoding.ASCII.GetBytes(readNama());
stream.Write(mssg, 0, mssg.Length);
}
else if (data == "ip")
{
byte[] mssg = System.Text.Encoding.ASCII.GetBytes(GetFQDN());
stream.Write(mssg, 0, mssg.Length);
}
}
// Shutdown and end connection
client.Close();
}
}
catch (SocketException se)
{
bw.ReportProgress(0, String.Format("SocketException: {0}", se));
}
}
}
private void FormServer_FormClosing(object sender, FormClosingEventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
savePath(openFileDialog1.FileName.ToString());
saveNama(openFileDialog1.SafeFileName.ToString());
//folderBrowserDialog1.ShowDialog();
//savePath(folderBrowserDialog1.SelectedPath.ToString());
label1.Text = readPath();
label2.Text = readNama();
label4.Text = UNCPathing.GetUNCPath(readPath());
}
private void savePath(string fPath)
{
string sPath = "Path.misc";
File.WriteAllText(sPath, fPath);
}
private string readPath()
{
string readText = File.ReadAllText("Path.misc");
return readText;
}
private void saveNama(string nama)
{
string sNama = "Nama.misc";
File.WriteAllText(sNama, nama);
}
private string readNama()
{
string readText = File.ReadAllText("Nama.misc");
return readText;
}
}
}
and this my client
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Client
{
public partial class FormClient : Form
{
public FormClient()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
label1.Text = IPAddressCheck();
label2.Text = GetFQDN();
label3.Text = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
}
public void msg(string mesg)
{
lstProgress.Items.Add(">> " + mesg);
}
public static string GetFQDN()
{
string domainName = IPGlobalProperties.GetIPGlobalProperties().DomainName;
string hostName = Dns.GetHostName();
if (!hostName.EndsWith(domainName)) // if hostname does not already include domain name
{
hostName += "." + domainName; // add the domain name part
}
return hostName; // return the fully qualified name
}
private static string IPAddressCheck()
{
IPHostEntry IPAddr;
IPAddr = Dns.GetHostEntry(GetFQDN());
IPAddress ipString = null;
foreach (IPAddress ip in IPAddr.AddressList)
{
if (IPAddress.TryParse(ip.ToString(), out ipString) && ip.AddressFamily == AddressFamily.InterNetwork)
{
break;
}
}
return ipString.ToString();
}
private void button1_Click(object sender, EventArgs e)
{
string message = textBox1.Text;
try
{
// Create a TcpClient.
// Note, for this client to work you need to have a TcpServer
// connected to the same address as specified by the server, port
// combination.
Int32 port = 1337;
string IPAddr = textBox2.Text;
TcpClient client = new TcpClient(IPAddr, port); //Unsure of IP to use.
// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
// Get a client stream for reading and writing.
// Stream stream = client.GetStream();
NetworkStream stream = client.GetStream();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);
//lstProgress.Items.Add(String.Format("Sent: {0}", message));
// Receive the TcpServer.response.
// Buffer to store the response bytes.
data = new Byte[256];
// String to store the response ASCII representation.
String responseData = String.Empty;
// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
if (message == "file")
{
lstProgress.Items.Add(String.Format("{0}", responseData));
fPath.getPath = (String.Format("{0}", responseData));
label4.Text = UNCPathing.GetUNCPath(fPath.getPath);
}
else if(message == "nama")
{
lstProgress.Items.Add(String.Format("{0}", responseData));
fPath.getNama = (String.Format("{0}", responseData));
}
// Close everything.
stream.Close();
client.Close();
}
catch (ArgumentNullException an)
{
lstProgress.Items.Add(String.Format("ArgumentNullException: {0}", an));
}
catch (SocketException se)
{
lstProgress.Items.Add(String.Format("SocketException: {0}", se));
}
}
private void button2_Click(object sender, EventArgs e)
{
//using (NetworkShareAccesser.Access(GetFQDN(), IPAddressCheck(), "arif.hidayatullah28#gmail.com", "971364825135win8"))
//{
// File.Copy("\\\\"+label1.Text+"\\TestFolder\\"+fPath.getNama+"", #"D:\movie\"+ fPath.getNama+"", true);
//}
}
private void button3_Click(object sender, EventArgs e)
{
string connString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\ARIF-PC\aaaaaaaaaa\MsAccess.accdb; Jet OLEDB:Database Password=dbase;";
string cmdText = "SELECT kode, deskripsi, stok, Harga FROM [Barang] ORDER BY kode DESC";
OleDbConnection conn = new OleDbConnection(connString);
OleDbCommand cmd = new OleDbCommand(cmdText, conn);
try
{
conn.Open();
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable barang = new DataTable();
da.Fill(barang);
dataGridView1.DataSource = barang;
}
finally
{
conn.Close();
}
}
}
}
but as you can see, I have to know the server ip address, is there a way to make the server and client autodiscover??
I've try this, worked with one PC but with a LAN it failed.
This that I've tried
Sorry form my bad English
On the client send a UDP broadcast 192.168.1.255 (this assumes you are operating on a class C network 192.168.1/24). The server then listens for the broadcast from any clients and then sends back a directed UDP packet to the client. The client is listening for this and decodes the packet which contains the address of the server.
This link C# How to do Network discovery using UDP Broadcast and some Google Fu will produce many examples of how to implement this.

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

SocketException when connecting to server

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

Categories