本帖最后由 黑马晓志 于 2014-3-9 16:00 编辑
客户端代码
- package com.xiaozhi.jingtian.tcp;
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.OutputStreamWriter;
- import java.net.Socket;
- public class UploadClient {
- public static void main(String[] args) throws Exception, IOException {
- //创建客户端的Socket服务,指定目的主机和端口号
- Socket socket=new Socket("121.251.158.251",10000);
-
- BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(new FileInputStream("c://1.txt")));
- BufferedWriter bufferedWriter= new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
-
- String line=null;
- while((line=bufferedReader.readLine())!=null){
- bufferedWriter.write(line);
- bufferedWriter.newLine();
- bufferedWriter.flush();
- }
-
- socket.shutdownOutput();
-
- bufferedReader.close();
- bufferedWriter.close();
- socket.close();
- }
- }
复制代码
服务端代码
- package com.xiaozhi.jingtian.tcp;
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.OutputStreamWriter;
- import java.net.ServerSocket;
- import java.net.Socket;
- import javax.xml.crypto.Data;
- public class UploadServer {
- public static void main(String[] args) throws Exception {
- //创建服务端的Socket服务,指定端口号
- ServerSocket serverSocket=new ServerSocket(10000);
-
- while(true){
- //通过accept方法获取连接过来的Socket对象
- Socket socket=serverSocket.accept();
- new MyThread(socket).start();
- }
-
- }
- }
- class MyThread extends Thread{
- private Socket socket;
-
- public MyThread(Socket socket) {
- this.socket = socket;
- }
- @Override
- public void run() {
- try {
- System.out.println(socket.getInetAddress().getHostAddress()+"上传文件");
- BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
- BufferedWriter bufferedWriter=new BufferedWriter(new OutputStreamWriter(new FileOutputStream("c://"+System.currentTimeMillis()+".txt")));
-
- String line=null;
- while((line=bufferedReader.readLine())!=null){
- bufferedWriter.write(line);
- bufferedWriter.newLine();
- bufferedWriter.flush();
- }
-
- System.out.println("上传成功");
- bufferedReader.close();
- bufferedWriter.close();
- socket.close();
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
复制代码 看毕老师的视频,说没有这行代码 socket.shutdownOutput();,客户端服务端会互相等待,因为没有结束标志-1.
可是我这里没有这行代码并没有出现互相等待的现象???
|