`

socket 传输文件

    博客分类:
  • JAVA
 
阅读更多

1.客户端

 

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class ClientMain {

	public ClientMain() {
		try {
			Socket s = new Socket("127.0.0.1", 30102);
			File file = new File("H:\\abc.txt");
			FileInputStream in = new FileInputStream(file);
			OutputStream out = s.getOutputStream();
			int b = -1;
			while((b = in.read()) != -1){
				out.write(b);
			}
			out.flush();
			s.close();
			in.close();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

public static void main(String[] args) {
		new ClientMain();
	}
	
}

 2.服务端

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerMain {

	public ServerMain() {
		try {
			File file = new File("F:\\abc.txt");
			FileOutputStream out = new FileOutputStream(file);
			ServerSocket ss = new ServerSocket(30102);
			Socket s = ss.accept();
			InputStream in = s.getInputStream();
			int b = -1;
			while((b = in.read()) != -1){
				out.write(b);
			}
			// 当客户端断开连接Socket.close()时,服务器端接收到了一个结束标志(-1)
			System.out.println(b);
			s.close();
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		new ServerMain();
	}

}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics