黑马程序员技术交流社区
标题:
网络编程TCP对文件上传
[打印本页]
作者:
逆世界ylm
时间:
2014-12-21 15:13
标题:
网络编程TCP对文件上传
package com.ccsu.net;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* 使用TCP完成文件的上传
* @author Administrator
*
*/
class Server5
{
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(8888);
Socket s = ss.accept();
PrintWriter p = new PrintWriter(s.getOutputStream(),true);
String ip = s.getInetAddress().getHostAddress();
System.out.println(ip+"...connected");
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter out = new PrintWriter(new FileWriter("d:\\test\\Server5.txt"),true);
String line = null;
while((line=br.readLine()) != null)
{
out.println(line);
}
//s.shutdownInput();
p.println("上传成功");
br.close();
s.close();
}
}
class Client5
{
public static void main(String[] args) throws UnknownHostException, IOException, InterruptedException {
Socket s = new Socket("127.0.0.1",8888);
BufferedReader br = new BufferedReader(new FileReader("d:\\test\\Bean.java"));
BufferedReader brin = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter p = new PrintWriter(s.getOutputStream(),true);
String line = null;
while((line=br.readLine()) != null)
{
p.println(line);
}
s.shutdownOutput();
//Thread.sleep(1000);
System.out.println(brin.readLine());
brin.close();
br.close();
s.close();
}
}
复制代码
为什么客户端发送数据后要关闭Socket输出流,而服务端不要关闭Socket输入流
作者:
bjuth
时间:
2014-12-21 15:25
你服务器端的代码里 缺少 while(true)循环接收
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2