多线程出现NullPointerException怎么解决?
我想做一个实时聊天程序,用线程send发送数据,用线程receive接收数据;当任一方输入end时断开连接。编译通过,运行时,只要客户端一连接上服务端,就出现NullPointerException。哪位大侠告诉我是怎么回事啊?谢谢!
代码如下:
server.java:
import java.io.*;
import java.net.*;
public class server{
static ServerSocket ssk;
static Socket csk;
public static void main(String args[]){
int p=0;
try{ ssk=new ServerSocket(10000);
csk=ssk.accept();
System.out.println("Connected.");
send thread1=new send();
receive thread2=new receive();
thread1.start();
thread2.start();
while(thread1.isAlive()!=false||thread2.isAlive()!=false){
p++;
p--;
}
csk.close();
ssk.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
class send extends Thread{
public void run(){
try{
BufferedReader LocalWords=new BufferedReader(new InputStreamReader(System.in));
synchronized(server2.csk){PrintWriter OutClient=new PrintWriter(server2.csk.getOutputStream());
String words;
words=LocalWords.readLine();
while(!words.equals("end")){
OutClient.println(words);
OutClient.flush();
System.out.println("Me:"+words);
words=LocalWords.readLine();
}
OutClient.close();}
}
catch(Exception e){
System.out.println(e);
}
}
}
class receive extends Thread{
public void run(){
try{
synchronized(server2.csk){BufferedReader InClient=new BufferedReader(new InputStreamReader(server2.csk.getInputStream()));
String receivings;
receivings=InClient.readLine();
while(!receivings.equals("end")){
System.out.println("Server:"+receivings);
receivings=InClient.readLine();
}
InClient.close();}
}
catch(Exception e){
System.out.println(e);
}
}
}
client.java:
import java.io.*;
import java.net.*;
public class client2 {
static Socket csk;
public static void main(String args[]){
int p=0;
try{csk=new Socket("localhost",10000);
System.out.println("Connected.");
send thread1=new send();
receive thread2=new receive();
thread1.start();
thread2.start();
while(thread1.isAlive()!=false||thread2.isAlive()!=false){
p++;
p--;
}
csk.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
class send extends Thread{
public void run(){
try{
BufferedReader Localwords=new BufferedReader(new InputStreamReader(System.in));
synchronized(client2.csk){ PrintWriter OutServer=new PrintWriter(client2.csk.getOutputStream());
String words;
words=Localwords.readLine();
while(!words.equals("end")){
OutServer.println(words);
OutServer.flush();
System.out.println("Me:"+words);
words=Localwords.readLine();
}
OutServer.close();}
}
catch(Exception e){
System.out.println(e);
}
}
}
class receive extends Thread{
public void run(){
try{synchronized(client2.csk){BufferedReader InServer=new BufferedReader(new InputStreamReader(client2.csk.getInputStream()));
String receivings;
receivings=InServer.readLine();
while(!receivings.equals("end")){
System.out.println("Server:"+receivings);
receivings=InServer.readLine();
}
InServer.close();}
}
catch(Exception e){
System.out.println(e);
}
}
}