有如下代码文件:
import java.io.*;
import java.net.*;
public class Text9 {
public static void main(String[] args) {
//开启两个线程来模拟TCP客户端和服务器端
new Thread(new TcpService()).start();
new Thread(new TcpClient()).start();
}
}
public class TcpService implements Runnable {
//服务器端
PrintWriter pw=null;
BufferedReader br=null;
ServerSocket ss=null;
Socket s=null;
@Override
public void run() {
try{
ss=new ServerSocket(8001);
s=ss.accept();
//读取客户端的字节流转换为缓冲字符流
br=new BufferedReader(new InputStreamReader(s.getInputStream()));
/*将客户端的数据写入服务器端*/
pw=new PrintWriter(new FileWriter("upload.txt"),true);
String line=null;
while((line=br.readLine())!=null)
{
pw.println(line);
}
PrintWriter bw=new PrintWriter(s.getOutputStream(),true);
bw.println("上传成功");
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
pw.close();
try
{
br.close();
ss.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
public class TcpClient implements Runnable {
//客户端
Socket s=null;
BufferedReader br=null;
PrintWriter pw=null;
public void run()
{
try
{
s=new Socket("127.0.0.1",10003);
/*读取上传文件*/
br=new BufferedReader(new FileReader("..//exam//src//com//itheima//exercise.txt"));
/*将上传文件写入网络流*/
pw=new PrintWriter(s.getOutputStream(),true);
String line=null;
while((line=br.readLine())!=null)
{
pw.println(line);
}
s.shutdownOutput();//返回传输结束标记
/*读取服务器端的反馈信息*/
BufferedReader bfrd=new BufferedReader(new InputStreamReader(s.getInputStream()));
String str=bfrd.readLine();
System.out.println(str);
}catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
br.close();
s.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
但程序结果是出现这样的异常:
java.net.BindException: Address already in use: JVM_Bind
at java.net.PlainSocketImpl.socketBind(Native Method)
at java.net.PlainSocketImpl.bind(PlainSocketImpl.java:359)
at java.net.ServerSocket.bind(ServerSocket.java:319)
at java.net.ServerSocket.<init>(ServerSocket.java:185)
at java.net.ServerSocket.<init>(ServerSocket.java:97)
at com.itheima.TcpService.run(TcpService.java:18)
at java.lang.Thread.run(Thread.java:619)
Exception in thread "Thread-0" java.lang.NullPointerException
at com.itheima.TcpService.run(TcpService.java:40)
at java.lang.Thread.run(Thread.java:619)
java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:519)
at java.net.Socket.connect(Socket.java:469)
at java.net.Socket.<init>(Socket.java:366)
at java.net.Socket.<init>(Socket.java:180)
at com.itheima.TcpClient.run(TcpClient.java:15)
at java.lang.Thread.run(Thread.java:619)
java.lang.NullPointerException
at com.itheima.TcpClient.run(TcpClient.java:40)
at java.lang.Thread.run(Thread.java:619)
这个异常怎么解决?????????????????
|
|