服务器端
package com.haoran.lesson02;
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 TcpServerDemo02 {
public static void main(String[] args) throws Exception {
//创建端口
ServerSocket serverSocket = new ServerSocket(9000);
//监听客户端的连接,阻塞式监听,会一直等待客户端的请求,
Socket accept = serverSocket.accept();
//获取输入流
InputStream inputStream = accept.getInputStream();
//新建管道输出流
FileOutputStream fileOutputStream = new FileOutputStream(new File("receive.jpg"));
???????//文件输出
byte[] buffer = new byte[1024];
int length;
while ((length=inputStream.read(buffer))!=-1){
fileOutputStream.write(buffer,0,length);
}
fileOutputStream.close();
inputStream.close();
accept.close();
serverSocket.close();
}
}
客户端
package com.haoran.lesson02;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
//=========在客户端发送文件=============
public class TcpClientDemo02 {
public static void main(String[] args) throws Exception {
//连接服务器,首先要知道服务器的ip地址以及端口号
InetAddress serverIP = InetAddress.getByName("127.0.0.1");
//通过ip地址和端口号,创建一个sock类,Socket是应用层与TCP/IP协议族通信的中间软件抽象层,它是一组接口。在设计模式中,Socket其实就是一个门面模式,它把复杂的TCP/IP协议族隐藏在Socket接口后面,对用户来说,一组简单的接口就是全部,让Socket去组织数据,以符合指定的协议。
Socket socket = new Socket(serverIP,9000);
//创建一个输出流—outputStream 发送消息IO流
OutputStream outputStream = socket.getOutputStream();
//读取文件
FileInputStream fileInputStream = new FileInputStream(new File("src/java.jpg"));
byte[] buffer=new byte[1024];
int length;
while((length=fileInputStream.read(buffer))!=-1){
outputStream.write(buffer,0,length);
}
fileInputStream.close();
outputStream.close();
socket.close();
}
}
|