Java_网络编程_TCP编程基本步骤(文件上传)

package cn.TCP;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 模拟上传文件
 * 1.指定端口 使用ServerSocket创建服务器
 * 2.阻塞式等待连接accept
 * 3.输入输出流操作
 * 4.释放资源
 * @author Chill Lyn
 *
 */
public class ServerUploadFile {
	public static void main(String[] args) throws IOException {
		System.out.println("server:");
//		1.指定端口 使用ServerSocket创建服务器
		ServerSocket server = new ServerSocket(9000);
//		2.阻塞式等待连接accept
		Socket client = server.accept();
		System.out.println("one connection!");
//		3.输入输出流操作
		InputStream is = new BufferedInputStream(client.getInputStream());
		OutputStream os = new BufferedOutputStream(new FileOutputStream("124.jpg"));
		byte[] flush = new byte[1024];
		int len = -1;
		while ((len = is.read(flush)) != -1) {
			os.write(flush, 0, len);
		}
		os.flush();
//		4.释放资源
		os.close();
		is.close();
		client.close();
	}
}

package cn.TCP;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * 模拟上传文件
 * 1.使用Socket创建客户端,指定服务器地址和端口,建立连接
 * 2.输入输出流操作
 * 3.释放资源 
 * @author Chill Lyn
 *
 */
public class ClientUploadFile {
	public static void main(String[] args) throws UnknownHostException, IOException {

//		1.使用Socket创建客户端,指定服务器地址和端口,建立连接
		Socket client = new Socket("localhost", 9000);
//		2.输入输出流操作
		InputStream is = new BufferedInputStream(new FileInputStream("123.jpg"));
		OutputStream os = new BufferedOutputStream(client.getOutputStream());
		byte[] flush = new byte[1024];
		int len = -1;
		while ((len = is.read(flush)) != -1) {
			os.write(flush, 0, len);
		}
		os.flush();
//		3.释放资源
		os.close();
		is.close();
		client.close();
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值