菜鸟,写了一段网络通信java代码,运行总是出错,求大神帮忙

ririkka369 ririkka369 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区

服务器的代码:

public class Server2 {
public static void main(String[] args) throws IOException {


ServerSocket ss=new ServerSocket(5900);
System.out.println("server start, wait first client");
while(true){
Socket s=ss.accept();
System.out.println("server ready");
new ServerThread(s).start();
}
}
}

-------------------------------------------------------------------------
线程代码:

public class ServerThread extends Thread {
Socket s;

public ServerThread(Socket s){
this.s=s;
}
public void run(){
Scanner scan = null;
BufferedReader br=null;
PrintWriter pw=null;
String str=null;
try {

br=new BufferedReader(new InputStreamReader(s.getInputStream()));
pw=new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
scan=new Scanner(System.in);
while(true){
str=br.readLine();
System.out.println("clent say: "+str);
System.out.println("server say: ");
str=scan.next();
pw.println(str);
pw.flush();
if(str.equals("exit")){
break;
}
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if(br!=null){
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(pw!=null){
pw.close();
}
if(s!=null){
try {
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

scan.close();
}
}
}
------------------------------------------------------------------------------------------
客户端代码:

public class Client {
public static void main(String[] args) {
Socket s=null;
BufferedReader br=null;
PrintWriter pw=null;
String str=null;
Scanner scan=new Scanner(System.in);

try {
s=new Socket(InetAddress.getLocalHost().getHostAddress(),5900);
br=new BufferedReader(new InputStreamReader(s.getInputStream()));
pw=new PrintWriter(new OutputStreamWriter(s.getOutputStream()));

while(true){
System.out.println("client speak now: ");
str=scan.next();
pw.println(str);
pw.flush();
str=br.readLine();
System.out.println("receiver from server: "+str);
if(str.equals("exit")){
break;
}
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if(br!=null){
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(pw!=null){
pw.close();
}
if(s!=null){
try {
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
scan.close();
}
}
}
----------------------------------------------------------------------
两个客户端进入后,一个退出,另一个不管再输入什么都报错。Exception in thread "main" java.lang.NullPointerException
at Client.main(Client.java:31)

求大神帮忙!!跪谢
...全文
评论 4
收藏 已收藏
分享
返回顶部
ririkka369
Java 51,407 成员 86,135 内容