I'm writing app on android, which would communicate with c# server via TCP protocol. My code works fine when I use wi-fi and now I want to change it that it would work even if android client would use mobile data
Server in c# (only recive and send data):
static void Main(string[] args)
{
//setup
Program prog = new Program();//to run non-static void from static context
//main server
try
{
IPAddress ipAd = IPAddress.Parse("192.168.x.xxx");
// Initializes the Listener
TcpListener myList = new TcpListener(ipAd, 11000);
/* Start Listeneting at the specified port */
myList.Start();
//label com
com:
//accept connection
Socket s = myList.AcceptSocket();
Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
//recive data
byte[] b = new byte[100];
int k = s.Receive(b);
char cc = ' ';
string text = null;//wil produce recived text
Console.Write("Recieved: ");
for (int i = 0; i < k - 1; i++)
{
Console.Write(Convert.ToChar(b[i]));
cc = Convert.ToChar(b[i]);
text += cc.ToString();
}
Console.WriteLine();
//analyze text
string reply = prog.analyzeText(text);
//send reply
ASCIIEncoding asen = new ASCIIEncoding();//is using to encode reply<string> to possible to send format
s.Send(asen.GetBytes(reply));//send
s.Close();
/* clean up */
goto com;
s.Close();
myList.Stop();
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.StackTrace);
Console.ReadLine();
}
}
and android client code:
private String connectSocket(String msg) {//send and receive data from server
try {
InetAddress serverAddr = InetAddress.getByName("192.168.x.xxx");
Socket socket = new Socket(serverAddr, 11000);
//define PrintWriter
PrintWriter out = null;
try {
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
final BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.println(msg);
String text = "";
String finalText = "";
while ((text = in.readLine()) != null) {
finalText += text;
}
socket.close();
return finalText;
} catch (Exception e) {
Toast.makeText(getApplicationContext(),"Something went wrong.\nTry again in few minutes",Toast.LENGTH_SHORT).show();
return "exception";
} finally {
socket.close();
}
} catch (UnknownHostException e) {
return "UnknownHostException";
} catch (IOException e) {
return "IOException";
}
}
PS. sorry for my english, but I started learning it only 1 year ago
There's no code changes needed. You might need to set up your network correctly so there's no firewalls in the way around your test server (and that may include talking to your ISP, if they have a firewall preventing incoming connections). But standard socket communication works over wifi or mobile.
Related
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
I've got a generic TCP Client and TCP Listener setup on my main laptop and my other laptop. The client and listener are their own separate programs, so I've had a client and server running on both laptops to try and get a simple instant messenger going.
The client and server will happily communicate with each other if both programs are executed on the same laptop. This is true for both my main and other laptop.
My main laptop's client will happily send messages to my other laptop, and the other laptop will gracefully receive messages from my main laptop.
However, when my other laptop's client sends a message to my main laptop's server it gets a timeout-related, communication-failed type of error. It just doesn't send the message.
Error message (caught by try-catch); "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 {my IP:port number}."
I'm getting the IP and port numbers correct, so rule that out.
There's no firewall business because the other laptop doesn't care at all about receiving messages from my main laptop.
I've also tried random port numbers and made sure that the client on my main laptop is connecting over the same port number that my other laptop's sever is listening on (or accepting messages from).
So why isn't my other laptop successfully sending messages to my main laptop?
The client asks for the user to enter an IP and then a port number. It then waits for the user to enter a message, then connects and sends that message to the IP via the given port number.
The server asks the user to enter a port number and prints messages received through that port.
Here's the code for the client program;
static void Main(string[] args)
{
string IP = localIPAddress();
Console.WriteLine("Your IP: " + IP); //provides IP number
Console.Write("Enter IP to connect to: ");
string connectToIP = Console.ReadLine();
if (connectToIP == "self")
{
connectToIP = localIPAddress();
// if I want to test both on the same computer
}
Console.WriteLine("\nEnter port number: ");
int portNo = int.Parse(Console.ReadLine());
while (true)
{
string message = Console.ReadLine();
try
{
// connection doesn't begin until ReadLine is done
request(connectToIP, portNo, message);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
public static string localIPAddress()
{
IPHostEntry host;
string localIP = "?";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
localIP = ip.ToString();
}
}
return localIP;
}
static void request(string address, int port, string message)
{
TcpClient client = new TcpClient();
client.SendTimeout = 1000;
client.ReceiveTimeout = 1000;
try
{
client.Connect(address, port);
StreamWriter sw = new StreamWriter(client.GetStream());
sw.WriteLine(message);
sw.Flush();
sw.Close();
}
catch (Exception a)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(a.Message.ToString());
Console.ResetColor();
}
}
Here's the code for the server;
static void Main(string[] args)
{
Console.WriteLine("Your IP: " + localIPAddress());
Console.Write("Enter port number you're receiving from: ");
int portNo = int.Parse(Console.ReadLine());
TcpListener listener = new TcpListener(IPAddress.Any, portNo);
Socket connection;
NetworkStream socketStream;
listener.Start();
while (true)
{
connection = listener.AcceptSocket();
connection.SendTimeout = 1000;
connection.ReceiveTimeout = 1000;
socketStream = new NetworkStream(connection);
try
{
respond(socketStream);
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
socketStream.Close();
connection.Close();
}
}
}
public static string localIPAddress()
{
IPHostEntry host;
string localIP = "?";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
localIP = ip.ToString();
}
}
return localIP;
}
static void respond(NetworkStream strm)
{
List<string> sentIn = new List<string>();
StreamReader sr = new StreamReader(strm);
while (sr.Peek() != -1)
sentIn.Add(sr.ReadLine());
sr.Close();
foreach (string s in sentIn)
{
Console.WriteLine(s);
}
}
Is there a problem with my code? There have been no Firewall-related messages when either laptop uses these programs.
It might be the sw.Flush() for the client, because that used to cause the sending process to freeze.
Thanks in advance. Once I get this problem sorted, I can start wondering how this can be used to make a multiplayer XNA game.
You might want to try making the timeouts a little longer (or remove them all together; they caused problems for me). Also, it's really a good idea to create a thread to receive messages while you handle the sending on the main thread.
Some notes:
You can use "loopback" or "127.0.0.1" if you'd like to connect to your local IP
if (connectToIP == "self")
{
connectToIP = localIPAddress();
// if I want to test both on the same computer
}
You really shouldn't connect, send a single message, and then disconnect, only to connect again.
Try something like this for the client:
using System.Threading;
static void Main(string[] args)
{
TcpClient client = new TcpClient();
Console.Write("IP: ");
string ip = Console.ReadLine();
Console.Write("Port: ");
int port = int.Parse(Console.ReadLine());
try
{
client.Connect(ip, port);
StreamWriter sw = new StreamWriter(client.GetStream());
sw.AutoFlush = true;
StreamReader sr = new StreamReader(client.GetStream());
Thread readThread = new Thread(() => readSocket(sr));
readThread.Start(); //Run readSocket() at the same time
string message = "";
while (message != "exit")
{
message = Console.ReadLine();
sw.WriteLine(message);
}
client.Close();
return;
}
catch (Exception e) { Console.WriteLine(e.ToString()); }
}
static void readSocket(StreamReader sr)
{
try
{
string message = "";
while ((message = sr.ReadLine()) != null)
{
Console.WriteLine(message);
}
}
catch (System.IO.IOException) { /*when we force close, this goes off, so ignore it*/ }
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
Here's an example of the Server:
static void Main(string[] args)
{
Console.Write("Port: ");
int port = int.Parse(Console.ReadLine());
TcpListener server = new TcpListener(IPAddress.Any, port);
try
{
server.Start();
TcpClient client = server.AcceptTcpClient();
StreamWriter sw = new StreamWriter(client.GetStream());
sw.AutoFlush = true;
StreamReader sr = new StreamReader(client.GetStream());
Thread readThread = new Thread(() => readSocket(sr));
readThread.Start();
string message = "";
while (message != "exit")
{
message = Console.ReadLine();
sw.WriteLine(message);
}
client.Close();
return;
}
catch (Exception e) { Console.WriteLine(e.ToString()); }
}
static void readSocket(StreamReader sr)
{
try
{
string message = "";
while ((message = sr.ReadLine()) != null)
{
Console.WriteLine(message);
}
}
catch (System.IO.IOException) { /*when we force close, this goes off, so ignore it*/ }
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
Here is the code for an Async server that forwards messages to all connected clients (If you were worried about not being able to share a port).
I'm trying to keep these examples simple, but it's probably a good idea to add more exception handling to all of them.
class Server
{
private int port;
private Socket serverSocket;
private List<StateObject> clientList;
private const int DEFAULT_PORT = 1338;
public Server()
{
this.port = 1338; //default port
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientList = new List<StateObject>();
}
public Server(int port)
{
this.port = port;
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientList = new List<StateObject>();
}
public void startListening(int port = DEFAULT_PORT)
{
this.port = port;
serverSocket.Bind(new IPEndPoint(IPAddress.Any, this.port));
serverSocket.Listen(1);
serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
}
private void AcceptCallback(IAsyncResult AR)
{
try
{
StateObject state = new StateObject();
state.workSocket = serverSocket.EndAccept(AR);
//Console.WriteLine("Client Connected");
clientList.Add(state);
state.workSocket.BeginReceive(state.buffer, 0, StateObject.BufferSize, SocketFlags.None, new AsyncCallback(ReceiveCallback), state);
serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
}
catch { }
}
private void ReceiveCallback(IAsyncResult AR)
{
StateObject state = (StateObject)AR.AsyncState;
Socket s = state.workSocket;
try
{
int received = s.EndReceive(AR);
if (received == 0)
return;
if (received > 0)
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, received));
string content = state.sb.ToString();
if (content.IndexOf(Environment.NewLine) > -1)
{
//Console.WriteLine(content);
foreach (StateObject others in clientList)
if (others != state)
others.workSocket.Send(Encoding.ASCII.GetBytes(content.ToCharArray()));
state.sb.Clear();
}
Array.Clear(state.buffer, 0, StateObject.BufferSize);
s.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
}
catch (Exception huh) {
s.Close();
s.Dispose();
//Console.WriteLine("Client Disconnected");
clientList.Remove(state);
return;
}
}
class StateObject
{
public Socket workSocket = null;
public const int BufferSize = 1024;
public byte[] buffer = new byte[BufferSize];
public StringBuilder sb = new StringBuilder();
}
}
I want to send a message from a C# application to the Android emulator or device over TCP. I have searched on Google and got the maximum results for Android client and C# server but not what I want to acheive.
Here is what I have tried; maybe I am going about it the wrong way but what I want is to send a message over TCP to an Android device.
Server Code to send a message:
private static int port = 4444;
private static TcpListener listener;
private static Thread thread;
private static int clientId = 0;
listener = new TcpListener(new IPAddress(new byte[] { 127, 0, 0, 1 }), port);
thread = new Thread(new ThreadStart(Listen));
thread.Start();
private static void Listen()
{
listener.Start();
MessageBox.Show("Listening on: " + port.ToString());
while (true)
{
MessageBox.Show("Waiting for connection....");
MessageBox.Show("Client No: " + clientId);
TcpClient client = listener.AcceptTcpClient();
Thread listenThread = new Thread(new ParameterizedThreadStart(ListenThread));
listenThread.Start(client);
}
}
private static void ListenThread(Object client)
{
NetworkStream netstream = ((TcpClient)client).GetStream();
MessageBox.Show("Request made");
clientId = clientId + 1;
// String message = "Hello world";
byte[] resMessage = Encoding.ASCII.GetBytes(clientId.ToString());
netstream.Write(resMessage, 0, resMessage.Length);
netstream.Close();
}
Client Code
private TextView textDisplay;
Socket socket;
private static final int TCP_SERVER_PORT = 4444;
ServerSocket ss = null;
try {
ss = new ServerSocket(TCP_SERVER_PORT);
//ss.setSoTimeout(10000);
//accept connections
Socket s = ss.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
//receive a message
String incomingMsg = in.readLine() + System.getProperty("line.separator");
Log.d("TcpServer", "received: " + incomingMsg);
textDisplay.append("received: " + incomingMsg);
//send a message
String outgoingMsg = "goodbye from port " + TCP_SERVER_PORT + System.getProperty("line.separator");
out.write(outgoingMsg);
out.flush();
Log.d("TcpServer", "sent: " + outgoingMsg);
textDisplay.append("sent: " + outgoingMsg);
//SystemClock.sleep(5000);
s.close();
} catch (InterruptedIOException e) {
//if timeout occurs
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
Log.d("Error",e.toString());
}
}
}
The problem lies in your Client code.
A socket is opened between two parties, one that plays the role of the listener / server that does bind->listen->accept and a client that connect
In your code there are two problems:
Your client should connect and not accept
Both your client and your server will try to read from the socket and write afterwards. There would be no problem if your read and write operations from the socket were on different threads.In your case this will result in a deadlock.
If you want both operations to be done on the same thread , sequentially then your client and server should perform the read and write in opposite order :
Client : read -> write
Server: write-> read
I am in desperate need of help. I have essentially created a program that (will use) encryption to send messages back and forth. The encryption part is working fine, however I am fairly new to Threads and I can not for the life of me get my Client/Server pieces of the application to line up. The chat program is direct IP connection using TCP, so each host is a client and a server. The issue I appear to be having, when I debug, is that the server thread is either not ready when the Client tries to connect to it, or if it is ready it will not relinquish the Thread so the Client can connect! I have been working on this for hours and it is very frustrating.. I hope someone can help! I've included my code below.
This is my code snippet from my MainForm, which constructs the Client and Server aspects:
private void InitializeComponent() {
server = new ServerSide("127.0.0.1",7865);
servThread = new Thread(new ThreadStart(server.begin));
client = new ClientSide("127.0.0.1",7865);
clientThread = new Thread(new ThreadStart(client.begin));
servThread.Start();
clientThread.Start();
//servThread.Join();
//clientThread.Join();
}
This is my ServerSide code:
public class ServerSide
{
String IpString;
int tcpPort;
bool goodToGo = false;
System.Net.IPAddress ipAddress = null;
public ServerSide(String ip, int tcpPort)
{
IpString = ip;
bool isValidIp = System.Net.IPAddress.TryParse(IpString, out ipAddress);
if (isValidIp == true) // check if the IP is valid, set the bool to true if so
{
goodToGo = true;
}
else
{
goodToGo = false;
}
}
public void begin()
{
try
{
IPAddress ipAd = IPAddress.Parse(IpString);
/* Initializes the Listener */
TcpListener myList = new TcpListener(ipAd, tcpPort);
Socket s = null;
/* Start Listening at the specified port */
while (true)
{
myList.Start();
if (myList.Pending())
{
s = myList.AcceptSocket();
break;
}
}
String toReceive = "";
while (true)
{
byte[] b = new byte[4096];
int k = s.Receive(b);
for (int i = 0; i < k; i++)
toReceive += Convert.ToString((Convert.ToChar(b[i])));
// ASCIIEncoding asen = new ASCIIEncoding();
var form = MainForm.ActiveForm as MainForm;
if (form != null)
{
form.messageReceived(toReceive);
}
toReceive = "";
}
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
}
}
}
ClientSide code:
public class ClientSide
{
private String IpString;
private int tcpPort;
private TcpClient tcpInt;
private static Stream stm;
private System.Net.IPAddress ipAddress = null;
private bool goodToGo = false;
public ClientSide(String ip, int tcpPort)
{
IpString = ip;
this.tcpPort = tcpPort;
bool isValidIp = System.Net.IPAddress.TryParse(IpString, out ipAddress);
if (isValidIp == true)
{
goodToGo = true;
}
else
{
goodToGo = false;
}
}
public void begin()
{
try
{
tcpInt = new TcpClient();
// Console.WriteLine("Connecting.....");
tcpInt.Connect(IpString, tcpPort);
// use the ipaddress as in the server program
// Console.WriteLine("Connected");
// String str = Console.ReadLine();
stm = tcpInt.GetStream();
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
}
public void sendMessage(String str)
{
// stm = tcpInt.GetStream();
ASCIIEncoding asen = new ASCIIEncoding();
byte[] ba = asen.GetBytes(str);
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]));*/
}
}
}
Once again.. what typically happens is my Client receives an error that the host actively refused the connection.. but I do not know how to time them. I am looking for how to have my server listening for TCP Connections, but still manage to go to my other thread to create the TCP Connecion to send the server (I am testing this on localhost currently).
Thanks.
In the constructor of the ServerSide class, you forgot to initialize the tcpPort member. Because you forgot, the server will try to listen to port 0 and the client will try to connect to port 7865, and it will fail.
Try adding this code to the constructor in the ServerSide class.
this.tcpPort = tcpPort;
As for the threads, you might have a problem if the client thread tries to connect before the server thread has started listening. You can use a loop to try to connect a number of times (let's say 10), with a timeout (let's say 1 second) if you don't succeed. This way, you will retry 10 times and give up after that.
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.