Tcp小练习:文件的传输。
客户端:
服务端:
首先运行服务端,然后运行客户端。客户端会把client.txt文件传给服务端,服务端把传过来的文件写在:server.txt里面。
运行效果:
[img]
[img]http://dl.iteye.com/upload/attachment/0081/9187/b6745fb7-0342-3139-82bc-5ea438604025.png[/img]
[/img]
看下client.txt下面多了一个server.txt,打开看下,里面的内容是一样的,说明文件复制成功。
[img]
[img]http://dl.iteye.com/upload/attachment/0081/9189/5bdb999b-a7c2-380f-9e92-a1c799da02dd.png[/img]
[/img]
客户端:
import java.net.*;
import java.io.*;
public class TcpClient {
public static void main(String[] args)throws Exception {
Socket s = new Socket("192.168.0.124",10005);
BufferedReader bufr = new BufferedReader(new FileReader("client.txt"));
//BufferedWriter buOut = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
PrintWriter out = new PrintWriter(s.getOutputStream(),true);
String line = null;
while((line=bufr.readLine())!=null){
//这里我刚开始的时候写的是out.write(line),出现问题:server.txt里面
//没有东西,是空的。必须要在后面加上“\r\n”和flush刷新。
//out.write(line+"\r\n");
//out.flush();
out.println(line);
}
//关闭客户端的输出流,相当于给流中加入一个结束标记-1。
s.shutdownOutput();
BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
String str = bufIn.readLine();
System.out.println(str);
bufr.close();
s.close();
}
}
服务端:
import java.net.*;
import java.io.*;
class TcpServer {
public static void main(String[] args)throws Exception {
ServerSocket ss = new ServerSocket(10005);
Socket s = ss.accept();
String ip = s.getInetAddress().getHostAddress();
System.out.println(ip+"---> connect");
BufferedReader bufin = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter out = new PrintWriter(new FileWriter("server.txt"),true);
String line = null;
while((line=bufin.readLine())!=null){
out.println(line);
}
PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
pw.println("上传成功");
out.close();
s.close();
ss.close();
}
}
首先运行服务端,然后运行客户端。客户端会把client.txt文件传给服务端,服务端把传过来的文件写在:server.txt里面。
运行效果:
[img]
[img]http://dl.iteye.com/upload/attachment/0081/9187/b6745fb7-0342-3139-82bc-5ea438604025.png[/img]
[/img]
看下client.txt下面多了一个server.txt,打开看下,里面的内容是一样的,说明文件复制成功。
[img]
[img]http://dl.iteye.com/upload/attachment/0081/9189/5bdb999b-a7c2-380f-9e92-a1c799da02dd.png[/img]
[/img]