1
我想在Java中實現一個可以支持多個客戶端的服務器 - 客戶端套接字程序,但是當我的客戶端連接到我的服務器時,執行多線程的類總是崩潰。Java中的多線程聊天服務器
import java.io.*;
import java.net.*;
public class ClientWorker extends Thread{
Socket cwsocket=null;
public ClientWorker(Socket cwsocket){
super("ClientWorker");
cwsocket=cwsocket;
}
public void run(){
try {
PrintWriter out = new PrintWriter(cwsocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(cwsocket.getInputStream()));
String serverinput, serveroutput="";
out.println(serveroutput);
while ((serverinput = in.readLine()) != null) {
out.println(serveroutput);
if (serveroutput.equals("Terminate"))
break;
}
out.close();
in.close();
cwsocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
每當我創建一個PrintWriter對象時,拋出一個NullPointerException異常,我不確定它爲什麼會繼續發生。以下是我的服務器和客戶端類。我究竟做錯了什麼?
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[]args)throws IOException{
ServerSocket serversocket=null;
final int PORT_NUM=4444;
boolean flag=true;
try{
System.out.println("Listening for connection");
serversocket=new ServerSocket(PORT_NUM);
}catch(IOException e){
System.out.println("Could not listen to port: "+PORT_NUM);
System.exit(-1);
}
while(flag){
new ClientWorker(serversocket.accept()).start();
}
System.out.println("Terminating server...");
serversocket.close();
}
}
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args){
Socket socket=null;
PrintWriter out=null;
BufferedReader in=null;
BufferedReader userInputStream=null;
String IP="127.0.0.1";
try{
socket = new Socket(IP, 4444);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException e) {
System.out.println("Unknown host:" + IP);
System.exit(1);
} catch (IOException e) {
System.out.println("Cannot connect to server...");
System.exit(1);
}
String userInput, fromServer;
try{
userInputStream = new BufferedReader(new InputStreamReader(System.in));
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
if (fromServer.equals("Terminate"))
break;
userInput = userInputStream.readLine();
if (userInput != null) {
System.out.println("> " + userInput);
out.println(userInput);
}
}
}catch(IOException e){
System.out.println("Bad I/O");
System.exit(1);
}
try{
out.close();
in.close();
userInputStream.close();
socket.close();
System.out.println("Terminating client...");
}catch(IOException e){
System.out.println("Bad I/O");
System.exit(1);
}catch(Exception e){
System.out.println("Bad I/O");
System.exit(1);
}
}
}
這看起來像是你的問題。我建議使用一個警告這些無用的任務的IDE(比如說Eclipse)。 – abyx 2009-09-17 06:53:08
很好。 +1 – 2009-09-17 08:34:48
Doh!我不能相信我忘了'這個'關鍵字。確實很好! – GobiasKoffi 2009-09-17 12:46:56