0
我已经编写了用于服务器和客户端套接字的代码。 我已经使用线程使用处理程序。但它经常会给出例外只有创建视图层次结构的原始线程可以触及其视图 如何管理来管理它?使用套接字通过Wi-Fi连接两台设备
下面是客户端的Socket用于服务器的Socket代码
public class ServerThread implements Runnable {
public void run() {
try {
Looper.prepare();
if (SERVERIP != null) {
handler.post(new Runnable() {
public void run() {
serverStatus.setText("Listening on IP: " + SERVERIP);
}
});
serverSocket = new ServerSocket(SERVERPORT);
Toast.makeText(getApplicationContext(), serverSocket.getLocalSocketAddress().toString()
, Toast.LENGTH_LONG).show();
serverStatus.append("\n"+serverSocket.getLocalSocketAddress().toString());
while (true) {
// listen for incoming clients
Socket client = serverSocket.accept();
serverStatus.setText("Connected.");
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
Log.d("ServerActivity", line);
handler.post(new Runnable() {
public void run() {
}
});
}
break;
} catch (Exception e) {
handler.post(new Runnable() {
public void run() {
serverStatus.setText("Oops. Connection interrupted. Please reconnect your phones.");
}
});
e.printStackTrace();
}
}
} else {
handler.post(new Runnable() {
public void run() {
serverStatus.setText("Couldn't detect internet connection.");
}
});
}
} catch (final Exception e) {
handler.post(new Runnable() {
public void run() {
serverStatus.setText("Error"+e.getMessage());
}
});
e.printStackTrace();
}
}
}
代码
public class ClientThread implements Runnable {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.d("ClientActivity", "C: Connecting...");
Socket socket = new Socket(serverAddr, 8080);
connected = true;
try {
console.append("\nC: Sending command.");
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
.getOutputStream())), true);
// where you issue the commands
out.println("Hey Server!");
console.append("C: Sent.");
} catch (Exception e) {
console.append("S: Error= "+ e.getMessage());
}
socket.close();
console.append("\nC: Closed.");
} catch (Exception e) {
Log.e("Client :", e.getMessage());
//console.append("\nC: Error= ");
connected = false;
}
}
}
这里控制台中,我试图把某些消息,文本视图。 我可以看到日志,但不是在文本视图
我已经使用了handler.i m不知道我是否已经使用它right.can你发布一些示例代码处理程序,其中UI therad从其他线程修改。 – 2011-05-22 11:39:44
@Nilesh Tupe:https://github.com/commonsguy/cw-android/tree/master/Threads/Handler – CommonsWare 2011-05-22 11:49:06
请在我的代码中建议更正或者给我一些评论,以便我能更好地理解我必须做的事情。 – 2011-05-22 12:10:54