我运行一个MainActivity类,我在其中添加了onClick事件,当我点击一个工厂时,它必须启动一个服务器系统的客户端类(服务器端在我的计算机上,这里没有涉及)。可悲的是,它崩溃了,我不明白为什么。 Fab2是一个浮动动作按钮。
public class MainActivity extends AppCompatActivity {
...
fab2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplication(), "Connect", Toast.LENGTH_SHORT).show();
ClientSide kb = new ClientSide();
kb.serverInitialization();
}
});
public class ClientSide extends Thread{
public static final String SERVER_HOSTNAME = "localhost";
public static final int SERVER_PORT = 2002;
private static BufferedReader mSocketReader;
private static PrintWriter mSocketWriter;
public void run(){System.out.println("run");}
public void serverInitialization() {
System.out.println("Thread activated!");
// Connect to the chat server
try {
Socket socket = new Socket(SERVER_HOSTNAME, SERVER_PORT);
mSocketReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
mSocketWriter = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
System.out.println("Connected to server " + SERVER_HOSTNAME + ":" + SERVER_PORT);
} catch (IOException ioe) {
System.err.println("Can not connect to " + SERVER_HOSTNAME + ":" + SERVER_PORT);
ioe.printStackTrace();
System.exit(-1);
}
// Start socket --> console transmitter thread
PrintWriter consoleWriter = new PrintWriter(System.out);
TextDataTransmitter socketToConsoleTransmitter = new TextDataTransmitter(mSocketReader, consoleWriter);
socketToConsoleTransmitter.setDaemon(false);
socketToConsoleTransmitter.start();
// Start console --> socket transmitter thread
BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));
TextDataTransmitter consoleToSocketTransmitter = new TextDataTransmitter(consoleReader, mSocketWriter);
consoleToSocketTransmitter.setDaemon(false);
consoleToSocketTransmitter.start();
}
}
class TextDataTransmitter extends Thread {
private BufferedReader mReader;
private PrintWriter mWriter;
public TextDataTransmitter(BufferedReader aReader, PrintWriter aWriter) {
mReader = aReader;
mWriter = aWriter;
}
/**
* Until interrupted reads a text line from the reader
* and sends it to the writer.
*/
public void run() {
try {
while (!isInterrupted()) {
String data = mReader.readLine();
MainActivity gg = new MainActivity();
gg.updateTextField(data);
mWriter.println(data);
mWriter.flush();
}
} catch (IOException ioe) {
System.err.println("Lost connection to server.");
System.exit(-1);
}
}
}
编译器跳转到Thread,所以我想这意味着它试图执行它... idk。请帮忙,我会尽力为您提供所需的信息。