问题
On Android I tried to implement a simple TCP Listener Thread (or copied it from anywhere). It should simply wait for a Text and then do something. The Text is sent, this part works, but this listener-Thread doesn´t even create the Socket for listening correctly.
Has anyone an Idea, whats wrong or another simple approach for me? The text is defined b myself and not html. I only found much too complicated http-handlers.
import java.lang.*;
import java.io.*;
import java.net.*;
public class Client implements Runnable {
public static void main(String args[]) {
System.out.print("Listening Thread started\n");
try {
Socket skt = new Socket("localhost", 2999);
BufferedReader in = new BufferedReader(new
InputStreamReader(skt.getInputStream()));
System.out.print("Received string: '");
while (!in.ready()) {}
System.out.println(in.readLine()); // Read one line and output it
System.out.print("'\n");
in.close();
}
catch(Exception e) {
System.out.print("Whoops! It didn't work!\n");
System.err.println(e);
}
}
public Client () {
}
@Override
public void run() {
// TODO Auto-generated method stub
main(null);
}
}
回答1:
The code you showed is used to create a client socket, not a server socket. see below an example of TCP server socket, taken from SystemBash:
class TCPServer
{
public static void main(String argv[]) throws Exception
{
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(6789);
while(true)
{
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println("Received: " + clientSentence);
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
}
}
}
来源:https://stackoverflow.com/questions/8298100/simple-tcp-listener-thread-for-android-mine-doesn%c2%b4t-connect