Tiago Tiago - 4 months ago 34
Android Question

Sockets - Communication between C# and JAVA Android

I have a JAVA application that is reading a message:

public void onClick(View view)
{
new Thread((new ClientThread())).start();
//Intent i = new Intent(MainActivity.this,Main2Activity.class);
// startActivity(i);
}

//Thread que inicia o socket
class ClientThread implements Runnable
{
@Override
public void run() {
try
{
InetAddress serveradress = InetAddress.getByName(server_IP);
Log.e("TCP","A conetar...");
socket = new Socket(serveradress,PORT);

BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while((mensagem = in.readLine()) != null)
{
mensagem_final += mensagem;
}
txt.setText(mensagem_final);

if(in.readLine() == null)
{
Log.e("TCP","Nao tem mensagens");
}
Log.e("MSG",mensagem);

socket.close();
}
catch (UnknownHostException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}

}
}


Now I'm trying to create a server in C# and all extra code is freezing when I run the server. And I still cant get the message from C# server.

Servidor servidor = new Servidor();
servidor.server();



class Servidor
{
public void server()
{

Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
TcpListener tcplistener = new TcpListener(IPAddress.Any, 6000);
tcplistener.Start();


TcpClient tcpclient = tcplistener.AcceptTcpClient();

byte[] data = new byte[1024];
NetworkStream ns = tcpclient.GetStream();

string welcome = "Ola";
data = Encoding.ASCII.GetBytes(welcome);
ns.Write(data, 0, data.Length);



}
}


Any help? I use Servidor servidor = new Servidor();
servidor.server(); in another windowsform. This window forms load another windowsforms and should also load the server. But everything on the windowsforms just freezes. Maybe I need threads?

Answer

AcceptTcpClient is a blocking call, and it really needs to be handled by something that spawns a new thread each time it succeeds, but for a single instance just try wrapping in a new thread e.g.

Task.Factory.StartNew(() =>
{
    Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    TcpListener tcplistener = new TcpListener(IPAddress.Any, 6000);
    tcplistener.Start();


    TcpClient tcpclient = tcplistener.AcceptTcpClient();

    byte[] data = new byte[1024];
    NetworkStream ns = tcpclient.GetStream();

    string welcome = "Ola";
    data = Encoding.ASCII.GetBytes(welcome);
    ns.Write(data, 0, data.Length);



});
Comments