谁能帮我看看这个程序那里有错么!总是出现java.lang.NullPointerException错误
import java.io.*;
import java.net.*;
public class ServerClient
{
public ServerClient(int port)
{
Server server=new Server(port);
server.start();
Client client=new Client(port);
client.start();
}
public static void main(String args[])
{
new ServerClient(7777);
}
}
class Server extends Thread
{
int port;
ServerSocket server;
Socket socket;
DataOutputStream outStream=null;
DataInputStream inStream=null;
public Server (int port)
{
try
{
this.port=port;
server=new ServerSocket(port);
}
catch(Exception e)
{
System.out.println(e.toString());
}
}
public void run()
{
try
{
socket=server.accept();
outStream=new DataOutputStream(socket.getOutputStream());
inStream=new DataInputStream(socket.getInputStream());
System.out.println("server is ok,please continue");
while(true)
{
String str=inStream.readUTF();
System.out.println("The server receive String:"+str);
outStream.writeUTF(str);
}
}
catch(Exception e)
{
System.out.println(e.toString());
}
}
}
class Client extends Thread
{
int port;
Socket socket;
DataInputStream inStream=null;
DataOutputStream outStream=null;
public Client(int port)
{
try
{
this.port=port;
socket=new Socket(InetAddress.getLocalHost(),port);
inStream=new DataInputStream(socket.getInputStream());
System.out.println("client is ok,please continue!");
}
catch(Exception e)
{
System.out.println(e.toString());
}
}
public void run()
{
try
{
while(true)
{
System.out.println("qingshuru");
byte[] b=new byte[1024];
String str="1";
//从键盘读取字符串
int m=System.in.read(b);
str=new String(b,0,0,m-1);
//向服务器发送信息
outStream.writeUTF(str);
//从服务器读取信息
str=inStream.readUTF();
System.out.println("The client receive String:"+str);
}
}
catch(Exception e)
{
System.out.println(e.toString());
}
}
}
------解决方案--------------------
在Client类的构造方法里面,要将outStream 变量初始化
- Java code
public Client(int port) { try { this.port = port; socket = new Socket(InetAddress.getLocalHost(), port); inStream = new DataInputStream(socket.getInputStream()); outStream = new DataOutputStream(socket.getOutputStream()); //若outStream 不初始化,后面的程序对它的调用肯定会报空指针异常了 System.out.println("client is ok,please continue!"); } catch (Exception e) { e.printStackTrace(); } }