Server closes connection when client sends a message - c#

I am trying to learn the server/client paradigm. I have created a server that listens for connection and input on given port.
My problem is that, when a client connects and sends a message, the server closes the connection, and stops listening for input. What I want, is that when a clients sends a message, the sever should not close the connection, but still keep getting input from the connected client. I know that I can only handle one client at a time, since I am not creating a Thread for each client, but this should not cause the server to close connection as soon as the client sends a message.
Here is my server code:
public void startServer() {
try {
IPAddress iAd = IPAddress.Parse("127.0.0.10");
TcpListener tcpListner = new TcpListener(iAd, 9000);
tcpListner.Start();
Console.WriteLine("The server is running on port: 9000");
Console.WriteLine("The local End point is: " + tcpListner.LocalEndpoint + "\nWaiting for a connection");
Socket socket = tcpListner.AcceptSocket();
Console.WriteLine("\nConnection from client: " + socket.RemoteEndPoint);
byte[] b =new byte[100];
int k = socket.Receive(b);
for (int i=0;i<k;i++) {
Console.Write("Recieved: " + Convert.ToChar(b[i]));
}
ASCIIEncoding asen=new ASCIIEncoding();
socket.Send(asen.GetBytes("The string was recieved by the server."));
Console.WriteLine("\nSent Acknowledgement");
/* clean up */
socket.Close();
tcpListner.Stop();
} catch(Exception e) {
Console.WriteLine(e.Message);
}
}
And the client code
public void StartClient(string servToConnectTo, int port) {
try{
client.Connect(servToConnectTo, port);
Console.WriteLine("Connected to server: " + servToConnectTo + " on port: " + port);
Console.WriteLine ("Write input to server...");
String input = Console.ReadLine();
Stream stream = client.GetStream();
ASCIIEncoding asen = new ASCIIEncoding();
byte[] b = asen.GetBytes(input);
Console.WriteLine("Sending...");
stream.Write(b, 0, b.Length);
byte[] bb = new byte[100];
int k = stream.Read(bb, 0, 100);
for(int i = 0; i < k; i++) {
Console.Write(Convert.ToChar(bb[i]));
}
client.Close();
} catch (Exception e) {
Console.WriteLine (e.Message);
}
}
I guess I need a while loop some place, but not sure where

Related

How to have a C# TCP Chat Server listen for connections from multiple clients?

So this is code for my TCP based chat server written in c#. It works no problem for connecting two computers via ipv4 for chat, but I am wanting the server program to listen for and accept, then send a "sucessfully joined" message to the computers that joined.
I am wondering is there a way to change this code to do this?
Server code:
IPAddress ipAd = IPAddress.Parse(IPV4.Text); //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();
MessageBox.Show("The server is running at port 8001...");
MessageBox.Show("The local End point is :" + myList.LocalEndpoint);
MessageBox.Show("Looking for other computer");
Socket s = myList.AcceptSocket();
Console.WriteLine("Found buddy " + s.RemoteEndPoint);
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes(satt.Text));
MessageBox.Show("The message " + satt.Text + " was sent to the computer with IP address " + IPV4.Text);
byte[] b = new byte[100];
int k = s.Receive(b);
for (int i = 0; i < k; i++)
Console.Write(Convert.ToChar(b[i]));
/* clean up */
s.Close();
myList.Stop();
Client code:
TcpClient tcpclnt = new TcpClient();
tcpclnt.Connect(RecieveIPAdd.Text, 8001); // use the ipaddress as in the server program
MessageBox.Show("Connected");
Stream stm = tcpclnt.GetStream();
MessageBox.Show("Listening for attack information......");
byte[] bb = new byte[100];
int k = stm.Read(bb, 0, 100);
string atk = Encoding.UTF8.GetString(bb.AsSpan(0, k));
Thank you.
// Code after help
private void Connectnattk_DoWork(object sender, DoWorkEventArgs e)
{
{
{
try
{
IPAddress ipAd = IPAddress.Parse(IPV4.Text); //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();
MessageBox.Show("The server is running at port 8001...");
MessageBox.Show("The local End point is :" + myList.LocalEndpoint);
MessageBox.Show("Looking for other computer");
Socket s = myList.AcceptSocket();
Console.WriteLine("Found buddy " + s.RemoteEndPoint);
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes(satt.Text));
MessageBox.Show("The command " + satt.Text + " was sent to the computer with IP address " + IPV4.Text);
byte[] b = new byte[100];
int k = s.Receive(b);
for (int i = 0; i < k; i++)
Console.Write(Convert.ToChar(b[i]));
void ServerStart()
{
TcpListener listener = new TcpListener(IPAddress.Any, 8001);
listener.Start();
Console.WriteLine("Listening on port: 8001");
while (true)
{
TcpClient client = listener.AcceptTcpClient();
ThreadPool.QueueUserWorkItem(state => HandleConnection(client));
}
}
void HandleConnection(TcpClient client)
{
Socket s = myList.AcceptSocket();
Console.WriteLine("Found buddy " + s.RemoteEndPoint);
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes(satt.Text));
Console.WriteLine("Number of connected buddies: " + connectedbuddies++);
client.Close();
}
/* clean up */
s.Close();
myList.Stop();
}
Accepting a client socket in your code is synchronous, so you can only accept one client, process it then loop around to accept and process another.
You can use threads to add parallelism to your code. You create a method for handling client sockets and create a new thread for the client socket. This will allow you to continue looping to accept new incoming client socket connections whilst processing existing client socket connections.
static void ServerStart()
{
TcpListener listener = new TcpListener(IPAddress.Any, 4480);
listener.Start();
Console.WriteLine("Listening on port: 4480");
while (true)
{
// Accept the client connection before creating the thread.
TcpClient client = listener.AcceptTcpClient();
ThreadPool.QueueUserWorkItem(state => HandleConnection(client));
}
}
static void HandleConnection(TcpClient client)
{
// Insert your code here. (Do not accept socket again here)
client.Close();
}
I create a new thread to run the HandleConnection method for each TcpClient using ThreadPool. You can create threads without ThreadPool however if threads are short-lived for performance reasons, you will want to use ThreadPool to create them.

c# client is trying to send information rather than listen, why is this happening?

So I am writing a c# client server program where the client receives information from the server, however the client appears to try to send information rather than receive after the successfully connect
public void SL_Click(object sender, EventArgs e)
{
try
{
TcpClient tcpclnt = new TcpClient();
tcpclnt.Connect(RecieveIP.Text, 8001); // use the ipaddress as in the server program
MessageBox.Show("Connected");
String str = Console.ReadLine();
Stream stm = tcpclnt.GetStream();
ASCIIEncoding asen = new ASCIIEncoding();
byte[] ba = asen.GetBytes(str);
MessageBox.Show("Listening for information......");
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]));
string toattk = str.ToString();
I think this, as the client and server do successfully connect, but the the message sent from the server is never actually recieved.
Server code for action when it connects and sends the message to the other computer:
private void Connectnattk_DoWork(object sender, DoWorkEventArgs e)
{
try
{
IPAddress ipAd = IPAddress.Parse(ipv4.Text); //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();
MessageBox.Show("The server is running at port 8001...");
MessageBox.Show("The local End point is :" + myList.LocalEndpoint);
MessageBox.Show("Looking for other computer");
Socket s = myList.AcceptSocket();
Console.WriteLine("Found buddy " + s.RemoteEndPoint);
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes(satt.Text));
MessageBox.Show("The command " + satt.Text + " was sent to the computer with IP address " + ipv4.Text);
byte[] b = new byte[100];
int k = s.Receive(b);
for (int i = 0; i < k; i++)
Console.Write(Convert.ToChar(b[i]));
/* clean up */
s.Close();
myList.Stop();
}
catch (Exception)
{
MessageBox.Show("Could not find other computer.");
}
They connect no problem, but the message sent from the server never appears on the client. I surmise this is because the client is trying to send a response back rather than receiving the message sent by the server. Or are there other reasons why the message is not received despite the computers connected? Thank you.

Cannot connect to another computer over TCP

I am working on a project that transfers files over TCP. It is written in .NET 4.7. The program works while the client connects on the server that is on the same computer but when I send it to a friend and I try to connect it I get an error:
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
Currently the program only sends some information about the file that will be copied and is nothing is encrypted as I cannot send even these information.
Here's the code for the server (Invoke is used because it is run on a separate thread):
private void Server_Start()
{
try
{
// Set port on 13000
int port = 13000;
//Get the ip adress for the server
String localIp;
using (var client = new WebClient())
{
// Try connecting to Google public DNS and get the local endpoint as IP
// If failed to connect set IP as local IP
if (CheckForInternetConnection())
{
try
{
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
{
socket.Connect("8.8.8.8", 65530);
IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
localIp = endPoint.Address.ToString();
}
}
catch (Exception e)
{
localIp = "127.0.0.1";
}
}
else
{
localIp = "127.0.0.1";
}
}
IPAddress IP = IPAddress.Parse(localIp);
// Create listener and start listening
server = new TcpListener(IP, port);
server.Start();
// Buffer for data
Byte[] bytes = new byte[256];
String data = string.Empty;
this.Invoke((MethodInvoker)(() => Log.Items.Add("Server started on ip: " + IP.ToString())));
while (true)
{
// Accepting requests
TcpClient client = server.AcceptTcpClient();
// Get the stream object
NetworkStream stream = client.GetStream();
// Read length of file name
byte[] nameLength = new byte[4];
stream.Read(nameLength, 0, 4);
int nameSize = BitConverter.ToInt32(nameLength, 0);
// Read the name of file
byte[] name = new byte[nameSize];
stream.Read(name, 0, nameSize);
String fileName = Encoding.UTF8.GetString(name);
// Read size of file
byte[] fileSizeB = new byte[4];
stream.Read(fileSizeB, 0, 4);
int fileSize = BitConverter.ToInt32(fileSizeB, 0);
// Read start signal
byte[] startB = new byte[9+1];
stream.Read(startB, 0, 9);
String start = Encoding.UTF8.GetString(startB);
this.Invoke((MethodInvoker)(() => Log.Items.Add("Size of name: " + nameSize.ToString())));
this.Invoke((MethodInvoker)(() => Log.Items.Add("Name of file: " + fileName)));
this.Invoke((MethodInvoker)(() => Log.Items.Add("File size: " + fileSize.ToString())));
this.Invoke((MethodInvoker)(() => Log.Items.Add("Start signal: " + start)));
// Response to client
byte[] message = Encoding.UTF8.GetBytes("Testmessage");
stream.Write(message, 0, message.Length);
}
server.Stop();
Log.Items.Add("Server started on ip: " + IP.ToString());
}
catch (Exception e)
{
this.Invoke((MethodInvoker)(() => Log.Items.Add(e)));
}
}
And here is the code for the client:
private void button1_Click(object sender, EventArgs e)
{
IPAddress iP = IPAddress.Parse(ConnectIp.Text);
int port = 13000;
int buffersize = 1024;
TcpClient client = new TcpClient();
NetworkStream netStream;
// Try to connect to server
try
{
client.Connect(new IPEndPoint(iP, port));
}
catch(Exception ex)
{
this.Invoke((MethodInvoker)(() => Log.Items.Add(ex.Message)));
return;
}
netStream = client.GetStream();
String path = "D:\\testingEnv\\test1\\testing\\Matematika\\2017\\Školsko\\2017-SS-skolsko-B-1234-zad.pdf";
String Filename = Path.GetFileName(path);
// We wish to send some data in advance:
// File name, file size, number of packets, send start and send end
byte[] data = File.ReadAllBytes(path);
// First packet contains: name size, file name, file size and "sendStart" signal
byte[] nameSize = BitConverter.GetBytes(Encoding.UTF8.GetByteCount(Filename)); // Int
byte[] nameB = Encoding.UTF8.GetBytes(Filename);
byte[] fileSize = BitConverter.GetBytes(data.Length);
byte[] start = Encoding.UTF8.GetBytes("sendStart");
// Last packet constains: "sendEnd" signal to stop reading netStream
byte[] end = Encoding.UTF8.GetBytes("sendEnd");
// Creating the first package: nameSize, fileName, fileSize and start signal
byte[] FirstPackage = new byte[4 + nameB.Length + 4 + 9];
nameSize.CopyTo(FirstPackage, 0);
nameB.CopyTo(FirstPackage, 4);
fileSize.CopyTo(FirstPackage, 4 + nameB.Length);
start.CopyTo(FirstPackage, 4 + nameB.Length + 4);
// Send the first pckage
netStream.Write(FirstPackage, 0, FirstPackage.Length);
byte[] buffer = new byte[30];
// Read the response
netStream.Read(buffer, 0, 11);
netStream.Close();
client.Close();
}
A friend tried to port forward the port 13000 but it didn't work either. We even tried with the firewall being down but nothing. I searched on the internet but couldn't find any solutions to the problem.
One thing to note is that both functions are in the same application. I don't know if that is the cause of the problem.
Does anyone know how what is the problem here?
Thanks in advance
Have you tried to connect to your server with telnet ? "telnet localhost 13000" or from other computer with correct ip and address nbr ? Try that while debugging your server code. If telnet works, then client code has some problem..

c# length of data througth StreamWriter

I have written a code for client server using tcp/sockets in c# which is working perfectly fine. My problem is that why I am able to send only limited size data from client to server at a single instance.
Following is my server code
public class AsynchIOServer
{
// server port number
const int port = 8001;
// server ip address
const string ip = "127.0.0.1";
const int maxBuffer = 10000;
static IPAddress ipAddress = IPAddress.Parse(ip);
static TcpListener tcpListener = new TcpListener(ipAddress, port);
static void Listeners()
{
try
{
Socket socketForClient = tcpListener.AcceptSocket();
if (socketForClient.Connected)
{
Console.WriteLine("Client : " + socketForClient.RemoteEndPoint + " is now connected to server.");
NetworkStream networkStream = new NetworkStream(socketForClient);
System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(networkStream);
System.IO.StreamReader streamReader = new System.IO.StreamReader(networkStream);
while (true)
{
string theString = streamReader.ReadLine();
if (theString != "exit")
{
// original message from client
Console.WriteLine("------------------------------------------------------------------------------");
Console.WriteLine("Message recieved from client(" + socketForClient.RemoteEndPoint + ") : " + theString);
// ASCII code for the message from client
Console.Write("ASCII Code for message is : ");
foreach (char c in theString)
{
Console.Write(System.Convert.ToInt32(c) + " ");
}
// Hex value of message from client
string hex = "";
foreach (char c in theString)
{
int tmp = c;
hex += String.Format("{0:x2}", (uint)System.Convert.ToUInt32(tmp.ToString()));
}
Console.WriteLine();
Console.WriteLine("Hex Code for the message from client : " + hex);
//sending acknowledgement to client
Console.WriteLine();
socketForClient.Send(new ASCIIEncoding().GetBytes(/*"The string was recieved from Client(" + socketForClient.RemoteEndPoint + ") : " + */theString));
} // end of if loop
// if exit from client
else
{
Console.WriteLine();
Console.WriteLine("Client " + socketForClient.RemoteEndPoint + " has exited");
break;
}
} // end of while loop
streamReader.Close();
networkStream.Close();
streamWriter.Close();
} // end of if loop
socketForClient.Close();
Console.WriteLine();
// Console.WriteLine("Press any key to exit from server program");
Console.ReadKey();
} // end of try loop
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
Console.WriteLine("Message not received from client");
}
} // end of Listener loop
// Number of clients that can connect to the server
public static void Main()
{
tcpListener.Start();
Console.WriteLine("********** This is the Server program **********");
Console.Write("Number of Clients that can connect to Server : ");
int numberOfClientsYouNeedToConnect = int.Parse(Console.ReadLine());
for (int i = 0; i < numberOfClientsYouNeedToConnect; i++)
{
Thread newThread = new Thread(new ThreadStart(Listeners));
newThread.Start();
}
Console.WriteLine();
} // end of Min Loop
} // end of public class AsynchIOServer
while my client code is
public class Client
{
// For acknowledgement from server
const int maxBuffer = 1000;
static public void Main(string[] Args)
{
// ip address of server to which client should be connected
string ip;
// port number at which server is listening for client connection
int port;
Console.Write("Enter the ip address: ");
ip = Console.In.ReadLine();
Console.Write("Enter the port number: ");
port = int.Parse(Console.In.ReadLine());
TcpClient socketForServer;
try
{
// connect to server at ipaddress ip and port number port
socketForServer = new TcpClient(ip, port);
}
catch
{
Console.WriteLine("Failed to connect to server at {0}:{1}", ip , port);
Console.ReadLine();
return;
}
// Initializing StreamReader and StreamWriter for sending or reading message from server
NetworkStream networkStream = socketForServer.GetStream();
System.IO.StreamReader streamReader = new System.IO.StreamReader(networkStream);
System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(networkStream);
try
{
Console.WriteLine();
Console.WriteLine("---Begin sending message(type 'exit' to disconnect from server)---");
Console.WriteLine();
Console.Write("Type message : ");
string str = Console.ReadLine();
while (str != "exit")
{
streamWriter.WriteLine(str);
streamWriter.Flush();
// For receiving acknowledgement from server
byte[] receiveBuffer = new byte[maxBuffer];
int k = networkStream.Read(receiveBuffer, 0, maxBuffer);
for (int i = 0; i < k; i++)
Console.Write(/*Convert.ToChar(*/receiveBuffer[i]);
Console.WriteLine();
Console.WriteLine("------------------------------------------------------");
Console.Write("Type message : ");
str = Console.ReadLine();
}
// For client to close connection with server
if (str == "exit")
{
streamWriter.WriteLine(str);
streamWriter.Flush();
}
} // end of try loop
catch
{
Console.WriteLine("Exception reading from Server");
}
// exit the client
networkStream.Close();
Console.WriteLine("Press any key to exit from client program");
Console.ReadKey();
} // End of Main loop
} // End of public class Client
Now when I run my program I enter following binary to be sent from client as first message
Type message : 11111111111111111111111111111111111111111111111111111111111111111
11111111111111111111111111111111111111111111111111111111111111111111111111111111
11111111111111111111111111111111111111111111111111111111111111111111111111111111
11111111111111111111111111111
Problem is that it doesn't allow me enter more binary data. I can send more binary data if I want to send by pressing enter and then sending as 2nd message. But I want to send it as single message. So is their any limit to send more data at single instance over tcp/sockets?
Your assessment of the problem is wrong. There are no messages -- TCP has no such thing as application-level messages because TCP is not a message protocol, it's a byte stream protocol that provides a stream of bytes, not messages. There is no such thing as "send it as single message" nor is there such as thing as "sending as 2nd message". It's just sending bytes and receiving bytes. If you want to receive more bytes, call receive again.
If you want to implement messages, you can do so. But you have to do it. You have to define, specify, and implement a protocol that sends and receives messages on top of TCP. You have to specify how messages will be delimited, send delimited messages, and write receive code to detect the delimiters and assemble the received byte stream into messages. It won't happen by itself.
The simplest solution is to read and write lines delimited by newline characters, assuming your "messages" can't contain newlines.
That has to do with the ReadLine method limiting input to 256 characters, see Remarks section for a workaround:
http://msdn.microsoft.com/en-us/library/system.console.readline.aspx
edit: typo

Server remains hang when sending

I'm writting a client(Android) - server(c#) application. I get the code from here:
How to make client on Android listen to server on C#?
Everythings is working fine, when i just send message from the client to server, and from server to client (closing the socket on server side). Now, what i want is : send message to server, receive message from server, then send again a message to server. The server hangs at sending the message. If i close the socket on server side after sending, it gives a dispose error, and i can's send the data from the server.
My server code is:
/*************************************SERVER*****************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace SERVER2
{
class Program
{
public static void Main()
{
try
{
IPAddress ipAd = IPAddress.Parse("192.168.2.102");
TcpListener myList = new TcpListener(ipAd, 18001);
myList.Start();
Console.WriteLine("The server is running at port 18001...");
Console.WriteLine("The local End point is :" +
myList.LocalEndpoint);
Console.WriteLine("Waiting for a connection.....");
m:
Socket s = myList.AcceptSocket();
Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
byte[] b = new byte[100];
int k = s.Receive(b);
char cc = ' ';
string test = null;
Console.WriteLine("Recieved1...");
for (int i = 0; i < k - 1; i++)
{
cc = Convert.ToChar(b[i]);
test += cc.ToString();
}
Console.WriteLine("Received characters1: "+test);
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes("The string was recieved by the server."));
Console.WriteLine("\nSent Acknowledgement");
//s.Close(); <-if i enable this, i get a dispose error
k = s.Receive(b);//i get dispose error here
cc = ' ';
test = null;
Console.WriteLine("Recieved2...");
for (int i = 0; i < k - 1; i++)
{
cc = Convert.ToChar(b[i]);
test += cc.ToString();
}
Console.WriteLine("Received characters2: " + test);
/* clean up */
goto m;
s.Close();
myList.Stop();
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.Message);
}
Console.ReadLine();
}
}
}
My client code is:
/******************************CLIENT*****************************************/
Socket socket = null;
try
{
Toast.makeText(context,"IP: "+ip+" port: "+port,10000).show();
InetAddress serverAddr = InetAddress.getByName(ip);
socket = new Socket(serverAddr, port);
}
catch (UnknownHostException e1)
{
Toast.makeText(context,"UnknownHostException ",10000).show();
}
catch (IOException e1)
{
Toast.makeText(context,"IOException ",10000).show();
}
String message = "1";
PrintWriter out = null;
BufferedReader in = null;
try {
Log.d("TCP", "C: Sending: '" + message + "'");
/*write*/
out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
out.println(message);
out.flush();
/*read*/
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String text = "";
String finalText = "";
while ((text = in.readLine()) != null)
{
finalText += text;
}
Toast.makeText(context, "FinalText: "+finalText, 10000).show();
Log.d("TCP", "C: Sent.");
Log.d("TCP", "C: Done.");
in.close();
/*write*/
out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
out.println(message);
out.flush();
} catch(Exception e) {
Log.e("TCP", "S: Error", e);
} finally {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Thanks advanced !!!
The reason you get the dispose error is because the s.close() closes the socket, and then your next s.Receive() is trying to read from a closed socket.
Also the hang you are seeing might be caused by in.close(); in your java code. It could be closing the underlying socket. Try commenting it out and see if that fixes your hanging problem.
Not an expert in C#, but I've done my share of socket programming.
Basically what you want is 1 + n threads.
One thread that just accepts connections.
For each socket that is returned by Socket s = myList.AcceptSocket(); you want a thread for sending/receiving data and processing the messages from the socket. You could also use two threads (one that sends, one that receives (this is the asynchronous case)).
You should use the stream of the tcp client.. an example can be found here: http://msdn.microsoft.com/de-de/library/system.net.sockets.tcplistener.aspx
And don't use goto, please.
You will never reach the end lines after goto m;
Surround the code with a while loop which checks if an timeout is occured or any other checks.
The reason why the server hangs is that he waits for 100 bytes to receive.
The problem was that when the client received the message from the server , in the while part entered into an infinite loop. I modify my app like this:
My client part:
try
{
Toast.makeText(context,"IP: "+ip+" port: "+port,10000).show();
InetAddress serverAddr = InetAddress.getByName(ip);
socket = new Socket(serverAddr, port);
}
catch (UnknownHostException e1)
{
Toast.makeText(context,"UnknownHostException ",10000).show();
}
catch (IOException e1)
{
Toast.makeText(context,"IOException ",10000).show();
}
String message = "HELLO FROM CLIENT";
PrintWriter out = null;
BufferedReader in = null;
try {
Log.d("TCP", "C: Sending: '" + message + "'");
/*write*/
OutputStream ostr=socket.getOutputStream();
OutputStreamWriter outputstr=new OutputStreamWriter(ostr);
BufferedWriter buffw=new BufferedWriter(outputstr);
out = new PrintWriter(buffw ,true);
out.println("HELLO 1 FROM CLIENT");
/*read - i modify to this*/
InputStreamReader reader=new InputStreamReader(socket.getInputStream());
char[] bytesreceived=new char[50];
reader.read(bytesreceived , 0, 50);
String text="";
for (int i=0;i<bytesreceived.length;i++)
{
text+=bytesreceived[i];
}
Toast.makeText(context, "Received1: "+text.trim(), 10000).show();
Log.d("IdealLog","Received1: "+text.trim());
/*write*/
out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
out.println("HELLO 2 FROM CLIENT");
/*read*/
reader=new InputStreamReader(socket.getInputStream());
bytesreceived=new char[50];
reader.read(bytesreceived , 0, 50);
text="";
for (int i=0;i<bytesreceived.length;i++)
{
text+=bytesreceived[i];
}
Toast.makeText(context, "Received2: "+text.trim(), 10000).show();
Log.d("IdealLog","Received2: "+text.trim());
} catch(Exception e) {
Log.e("TCP", "S: Error", e);
} finally {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
My server side code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace SocketServer
{
class Program
{
static void Main(string[] args)
{
IPEndPoint ip = new IPEndPoint(IPAddress.Any, 18001);
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(ip);
socket.Listen(10);
Console.WriteLine("Waiting for a client...");
Socket client = socket.Accept();
IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;
Console.WriteLine("Connected with {0} at port {1}", clientep.Address, clientep.Port);
string welcome = "HELLO 1 FROM SERVER";
byte[] data = new byte[200];
int receiveddata=client.Receive(data);
Console.WriteLine("Received data from CLIENT1: {0}", System.Text.ASCIIEncoding.ASCII.GetString(data).Trim());
ASCIIEncoding asen = new ASCIIEncoding();
byte[] data2 = new byte[200];
data2 = asen.GetBytes(welcome);
int sentdata=client.Send(data2, data2.Length, SocketFlags.None);
Console.WriteLine("Sent data from SERVER: {0}", welcome);
byte[] data3 = new byte[200];
Console.WriteLine("Receiving data from CLIENT : {0}", "...");
client.Receive(data3);
Console.WriteLine("Received data from CLIENT2: {0}", System.Text.ASCIIEncoding.ASCII.GetString(data3).Trim());
byte[] data4 = new byte[200];
data4 = asen.GetBytes("HELLO 2 FROM SERVER");
sentdata = client.Send(data4, data4.Length, SocketFlags.None);
client.Close();
socket.Close();
Console.WriteLine("Disconnected from {0}", clientep.Address);
Console.ReadLine();
}
}
}
Now, everything is working fine, without hang. The only problem is, that i don't know if this will work for receiving , sending files.

Categories

Resources