您的位置:首页 > 理论基础 > 计算机网络

tcp协议单用户图片上传

2016-04-24 21:09 309 查看
      tcp协议中,单张图片,一个客户端一个服务器端演示案例。

package com.neutron.network.tcp.file;

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

public class PictureServer {

public static void main(String[] args) throws IOException {
// 建立服务端的服务,ServerSocket,服务端服务绑定端口
ServerSocket server = new ServerSocket(10008);
// 获取连接过来的客户端,使用ServerSocket的accept方法,没有连接就会等待,阻塞式方法
Socket client = server.accept();
System.out.println("client " + client.getInetAddress().getHostAddress() + ":" + client.getPort());

// 获取客户端输入流
InputStream in = client.getInputStream();
// 创建文件输出流
FileOutputStream fos = new FileOutputStream("/home/zhanght/Downloads/vicopyx.png");
// 创建缓冲区
byte[] buff = new byte[1024];
int len = 0;
while ((len = in.read(buff)) != -1) {
fos.write(buff, 0, len);
}

// 获取客户端输出流
OutputStream out = client.getOutputStream();
out.write("上传成功".getBytes());

out.close();
fos.close();
in.close();
client.close();
server.close();
}

}
package com.neutron.network.tcp.file;

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.创建客户端服务
* 2.读取客户端图片信息
* 3.通过socket输出流将数据发送给服务器端
* 4.读取服务器反馈信息
* 5.关闭
* @author zhanght
*
*/
public class PictureClient {

public static void main(String[] args) throws UnknownHostException, IOException {
// 创建客户端,并且指定服务器端主机和端口
Socket client = new Socket("127.0.0.1", 10008);
// 创建文件输入流
FileInputStream fis = new FileInputStream("/home/zhanght/Downloads/vi.png");
// 获取客户端输出流
OutputStream out = client.getOutputStream();

int len = 0;
while ((len = fis.read()) != -1) {
out.write(len);
}
// 数据上传结束
client.shutdownOutput();

// 获取客户端输入流
InputStream in = client.getInputStream();
// 定义存储服务器端返回数据缓存
byte[] buff = new byte[1024];
int length = in.read(buff);
System.out.println(new String(buff, 0, length));

out.close();
fis.close();
client.close();
}

}
      主要目的:体验tcp协议中客户端和服务器端交互而已。实际开发不可能使用这么使用。    
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  网络编程 tcp