客户端代码
package com.xtsheng.TcpDemo;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
/**
* @author zxa
* @version 1.0
* @date 2020/12/8 19:46
*/
public class TcpClientTest {
public static void main(String[] args) {
try {
//创建socket连接 指定连接服务器ip+端口
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9999);
//获取socket输出流 将文件读取到输出流进行传输
OutputStream os = socket.getOutputStream();
//获取要被传输文件的输入流 将文件写入到输出流中
FileInputStream fis = new FileInputStream(new File("zza.jpg"));
byte[] bytes = new byte[1024];
int len;
while ((len=fis.read(bytes))!=-1){
os.write(bytes,0,len);
}
//告诉服务器写入到输出流中完毕
socket.shutdownOutput();
//关闭连接 其实应该放到finally中
fis.close();
os.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
服务端代码
package com.xtsheng.TcpDemo;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
* @author zxa
* @version 1.0
* @date 2020/12/8 19:53
*/
public class TcpServerTest {
public static void main(String[] args) {
try {
//创建服务器端socket 指定服务所在端口
ServerSocket serverSocket = new ServerSocket(9999);
//获取连接到服务器端的socket
Socket socket = serverSocket.accept();
//获取socket输入流
InputStream in = socket.getInputStream();
//指定写入文件的输出流 写入文件
FileOutputStream fos = new FileOutputStream(new File("zzzz.jpg"));
byte[] buffer = new byte[1024];
int len;
while ((len=in.read(buffer))!=-1){
fos.write(buffer,0,len);
}
fos.close();
in.close();
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}