1
Reply

About Socket Programming in c# windows application

Pramod Kumar Nandagiri

Pramod Kumar Nandagiri

Sep 9 2009 8:01 AM
6.3k

Hi, Iam doing socket programming in c# windows bellow is my code, one day it has worked fine and well but from next day it is not working and ethernet connection and everything are unchanged between these days , I am not getting what is the problem is, plese help me on this
It's working well if i run both server application and client appli from same system but it's not working when i run the client appli from other system and server from other system , one day the same code was worked fine but after the day it's not working
 
server code:
 
TcpListener tcpListener = new TcpListener(10);
tcpListener.Start();
Socket socketForClient = tcpListener.AcceptSocket();
if (socketForClient.Connected)
{
MessageBox.Show("Client connected");
NetworkStream networkStream = new NetworkStream(socketForClient);
System.IO.
StreamWriter streamWriter =
new System.IO.StreamWriter(networkStream);
System.IO.
StreamReader streamReader =
new System.IO.StreamReader(networkStream);
string theString = "Sending";
streamWriter.WriteLine(theString);
MessageBox.Show(theString);
streamWriter.Flush();
theString = streamReader.ReadLine();
MessageBox.Show(theString);
streamReader.Close();
networkStream.Close();
streamWriter.Close();
}
socketForClient.Close();
MessageBox.Show("Exiting...");
AND THIS IS MY CLIENT CODE
TcpClient
socketForServer;
try
{
socketForServer =
new TcpClient("192.168.1.6", 10); //here if i use "localhost" or ipaddress ie "192.168.1.6" and i run both server appli and client appli from same system the client succefully connected to server
//i changed the ipaddress of localhost and used the ipaddress of other system and client appli was run from the other sys (which sys ip is used) it's not connecting to server, but it was worked one day finely
//why iam asking like this is i don't know much about socket prog, i will be happy if any one helps me
// my aim is to send the data from one sys to other sys through ethernet
}
catch
{
MessageBox.Show("Failed to connect to server at {0}:999", "192.168.1.6");
return;
}
NetworkStream networkStream = socketForServer.GetStream();
System.IO.
StreamReader streamReader =
new System.IO.StreamReader(networkStream);
System.IO.
StreamWriter streamWriter =
new System.IO.StreamWriter(networkStream);
try
{
string outputString;
// read the data from the host and display it
{
outputString = streamReader.ReadLine();
MessageBox.Show(outputString);
streamWriter.WriteLine(
"Client Message");
MessageBox.Show("Client Message");
streamWriter.Flush();
}
}
catch
{
MessageBox.Show("Exception reading from Server");
}
// tidy up
networkStream.Close();

Answers (1)