public class Test { public static void main(String[] args)
{
ServerSocket server=null;
try
{
server=new ServerSocket(5432);
}
catch(IOException e )
{ }
OutputStream os;
InputStream is;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
DataOutputStream dos;
DataInputStream dis;
Socket s;
InetAddress address;
String receiveMsg=null;
String sendMsg=null;
while(true)
{
try
{
s=server.accept();
address=s.getInetAddress();
System.out.println(address+"linked...");
os=s.getOutputStream();
is=s.getInputStream();
dos=new DataOutputStream(os);
dis=new DataInputStream(is);
receiveMsg=dis.readUTF();
System.out.println("The message from client is:"+receiveMsg);
System.out.println("What is the message that we will send to the client:");
sendMsg=br.readLine();
dos.writeUTF(sendMsg);
dos.flush();
}
catch(IOException e)
{
e.printStackTrace();
} }
}
} 总是出现异常, s=server.accept();这句有异常,NullPointer异常。怎么回事啊
{
ServerSocket server=null;
try
{
server=new ServerSocket(5432);
}
catch(IOException e )
{ }
OutputStream os;
InputStream is;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
DataOutputStream dos;
DataInputStream dis;
Socket s;
InetAddress address;
String receiveMsg=null;
String sendMsg=null;
while(true)
{
try
{
s=server.accept();
address=s.getInetAddress();
System.out.println(address+"linked...");
os=s.getOutputStream();
is=s.getInputStream();
dos=new DataOutputStream(os);
dis=new DataInputStream(is);
receiveMsg=dis.readUTF();
System.out.println("The message from client is:"+receiveMsg);
System.out.println("What is the message that we will send to the client:");
sendMsg=br.readLine();
dos.writeUTF(sendMsg);
dos.flush();
}
catch(IOException e)
{
e.printStackTrace();
} }
}
} 总是出现异常, s=server.accept();这句有异常,NullPointer异常。怎么回事啊
不是这样吧。。
try
{
server=new ServerSocket(5432);
}
catch(IOException e )
{ } 看这里,创建socket的时候可能有异常,而你什么也没做,还让程序继续了下去!
如果出现异常了server并没有被创建的,仍然为null,后面调用就出现空指针异常了