我做了两个类,第一个是服务器类,它运行一个线程来等待并接受来自客户端的套接字连接。
第二个类是 EchoThread 类,它启动一个新线程,该线程获取套接字连接传递的文本消息。这样做的原因是因为它需要这样做,所以我可以一次将多个客户端连接到服务器。所以我创建了这个类。它在 Server 类的 while(true) 循环中调用,以在建立连接时启动一个新线程。
问题是这个应用程序的 logcat 是 EchoThread 类的 nullPointer 异常,在这一行:
handler.post(new Runnable() {
为什么我会收到此错误消息以及如何处理?
服务器类:
public class ServerThread implements Runnable {
public void run() {
try {
if (SERVERIP != null) {
handler.post(new Runnable() {
@Override
public void run() {
serverStatus = "Listening on IP: " + SERVERIP;
}
});
serverSocket = new ServerSocket(SERVERPORT);
while (true) {
// listen for incoming clients
Socket client = serverSocket.accept();
handler.post(new Runnable() {
@Override
public void run() {
Intent intent = new Intent();
intent.setAction("com.example.diceRolled");
intent.putExtra("serverStatus","Connected");
sendBroadcast(intent);
}
});
new EchoThread(Server.this, client).start();
} // end while(true) method
} else { // the rest of the code for Server class....
回声线程类:
public class EchoThread extends Thread {
protected Socket socket;
private String line;
private Handler handler;
private Context context;
private Socket client;
public EchoThread(Context c, Socket clientSocket) {
this.socket = clientSocket;
this.context = c;
}
public void run(){
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
while ((line = in.readLine()) != null) {
// Log.d("ServerActivity", line);
handler.post(new Runnable() {
private String receivedCommand;
@Override
public void run() {
receivedCommand = line;
Intent intent = new Intent();
intent.setAction("com.example.diceRolled");
intent.putExtra("serverStatus", line.trim());
context.sendBroadcast(intent);
Toast.makeText(context, "sent message " + receivedCommand, Toast.LENGTH_SHORT).show();
// the rest of the code for EchoThread class....