本帖最后由 Geek_001 于 2014-7-20 21:20 编辑
package com.itheima;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
// 使用TCP协议写一个可以上传文件的服务器和客户端。
public class Test9 {
public static void main(String[] args)throws Exception {
// TODO Auto-generated method stub
Socket s = new Socket("192.168.1.103",4000);
BufferedReader bufr = new BufferedReader(new FileReader("c:\\1.txt"));
PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
String line = null;
while((line=bufr.readLine())!=null)
{
pw.println(line);
}
BufferedReader bufrIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
String ln = bufrIn.readLine();
System.out.println(ln);
bufr.close();
s.close();
}
}
class ServerSocketDemo
{
public static void main(String[] args)throws Exception
{
ServerSocket ss = new ServerSocket(4000);
Socket s = ss.accept();
String ip = s.getInetAddress().getHostAddress();
System.out.println(ip+".........connected");
BufferedReader bufrIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter pw = new PrintWriter(new FileWriter("c:\\2.txt"),true);
String line = null;
while((line=bufrIn.readLine())!=null)
{
pw.println(line);
}
PrintWriter pwOut = new PrintWriter(s.getOutputStream());
pwOut.println("上传成功");
bufrIn.close();
s.close();
}
}
异常信息:Exception in thread "main" java.net.BindException: Address already in use: JVM_Bind
问题已解决;
方式:把服务端的 bufrIn.close();改为pw.close()和加上ss.close();同时改变客户端和服务端的端口,先运行服务端,再运行客户端即可
|
|