2014-01-18 166 views
1

我环顾四周,发现了这样做的不同方式,所有这些方式似乎都会产生错误。这是我想要运行的。它连接到已经运行的服务器。 关于如何使其工作或更改以使其工作的任何想法?在后台运行线程

String serverAddress = MainActivity.serverAddress; 
int port = MainActivity.newport; 
Socket socket = new Socket(serverAddress, port); 
in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
out = new PrintWriter(socket.getOutputStream(), true);   
String getName=MainActivity.name; 

// Process all messages from server, according to the protocol. 
while (true) { 
    String line = in.readLine(); 
    if (line.startsWith("SUBMITNAME")) { 
     out.println(getName); 
    } 
    else if (line.startsWith("NAMEACCEPTED")) { 
     //textField.setEditable(true); 
    } 
    else if (line.startsWith("MESSAGE")) { 
     mt.append(line.substring(8) + "\n"); 
    } 
} 
+0

你在哪里运行这段代码,有哪些错误?一个'AsyncTask'将是一个好主意。在'doInBackground()'中运行网络代码,并用任何其他方法更新'UI'。 – codeMagic

+0

使用线程处理程序或asynctask执行所有网络操作 – skyshine

回答

0

这是什么工作?它是代码本身,还是你需要帮助,以(true)循环的形式运行这个线程?

while(true)循环会占用主要的java线程,所以你不能在while循环之外执行任何其他操作。所以首先,我会建议通过实现runnable或创建一个匿名类并启动线程,将while循环内部的操作变为线程。

有很多的例子在此:Java - creating a new thread

希望这有助于!如果我把你的问题解释错了,请回复我。