0

现在我正在建立套接字连接以将多个客户端连接到一台服务器。一切都很好,我在不同的班级做线程。但是当我用线程活动中的字符串填充 textView 时,我不能。请帮忙

这个 MainActivity:

公共类 MainActivity 扩展 Activity {

private static int port = 6000;
TextView txt;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    txt = (TextView) findViewById(R.id.txtCommand);
    txt.setText("Server : ");
    ServerSocket server1 = null;
    Server gameServer = new Server();
    try {
        server1 = new ServerSocket(port);
        // .. server setting should be done here
    } catch (IOException e) {
        System.out.println("Could not start server!");
       // return ;
    }

    while (true) {
        Socket client = null;
        try {
            client = server1.accept();
            gameServer.handleConnection(client);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public class Server  {
    private ExecutorService executor = Executors.newCachedThreadPool();

    public void handleConnection(Socket client) throws IOException {    
        PlayerConnection newPlayer = new PlayerConnection(this, client);
        txt.setText(newPlayer.getuname());
        this.executor.execute(newPlayer);
    }

    // add methods to handle requests from PlayerConnection
}

和这个线程活动:

公共类 PlayerConnection 实现 Runnable { 私有服务器父级;

private Socket socket;
private PrintWriter out;
private BufferedReader in;
String line;

protected PlayerConnection(Server parent, Socket socket) throws IOException {
    this.parent = parent;
    this.socket = socket;

    this.in = new BufferedReader(new InputStreamReader(socket
            .getInputStream()));
    this.out = new PrintWriter(new OutputStreamWriter(
            socket.getOutputStream()));     
}

public void run() {
    while(!this.socket.isClosed()) {                        
        try {
            //int nextEvent = this.in.readInt();
            line = in.readLine();
            System.out.println("Server Receive : "
                    + line);
            out.println("Server Sent :" +line);
            System.out.println("SEND : "
                    + line);
            out.flush();
             if (line == null){
                 this.socket.isClosed();
                 break;
             }
        } catch (IOException e) {}
    }
4

2 回答 2

0

我意识到你有一个在你的 onCreate 方法中永远不会结束的 while 循环。尝试将该循环移动到您的线程中。此循环阻止您的应用程序的输入。

while (true) {
    Socket client = null;
    try {
        client = server1.accept();
        gameServer.handleConnection(client);
    } catch (IOException e) {
        e.printStackTrace();
    }
于 2012-11-06T11:02:00.597 回答
0

您可以使用处理程序或 runOnUiThread 方法。

于 2012-11-06T05:42:39.250 回答