import org.junit.jupiter.api.Test;
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
/**
* 服务端和客户端在本例中都有本机(127.0.0.1)充当
*/
public class TcpTest {
/**
* 模拟客户端:
* 发送本地图片到服务器,并接受服务器发过来的确认消息,打印在控制台
* 可循环上传
* 多线程处理客服端的上传请求
*/
@Test
public void client() {
Socket socket=null;
FileInputStream fi=null;
try {
InetAddress inetAddress=InetAddress.getLocalHost();
socket=new Socket(inetAddress,8888);
OutputStream so = socket.getOutputStream();
fi=new FileInputStream(new File("src/xn/socketTest/1.jpg"));
byte[] bytes=new byte[1024];
int len;
while ((len=fi.read(bytes))!=-1){
so.write(bytes,0,len);
}
socket.shutdownOutput();
InputStream si = socket.getInputStream();
byte[] bytes1=new byte[20];
int len1;
while ((len1=si.read(bytes1))!=-1){
System.out.println(new String(bytes1,0,len1));
}
}catch (Exception e){
e.printStackTrace();
}finally {
if(fi!=null){
try {
fi.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(socket!=null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 模拟服务器,接受来自客服端上传的图片,并保存在服务器的本地文件夹中
*/
@Test
public void server() throws IOException {
ServerSocket serverSocket = new ServerSocket(8888);
while (true){
Socket socket = serverSocket.accept();
new Thread(new Runnable() {
@Override
public void run() {
FileOutputStream fo=null;
try {
InputStream si = socket.getInputStream();
String filename=""+System.currentTimeMillis()+(Math.random()*99999+1);
fo=new FileOutputStream(new File("src/xn/xnjt/"+filename+".jpg"));
byte[] bytes=new byte[1024];
int len=0;
while ((len=si.read(bytes))!=-1){
fo.write(bytes,0,len);
}
OutputStream so = socket.getOutputStream();
so.write("照片已收到,嘻嘻!!".getBytes());
}catch (Exception e){
e.printStackTrace();
}finally {
if(fo!=null){
try {
fo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(socket!=null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}).start();
}
}
}
模拟客户端和服务端
于 2022-03-02 17:28:22 首次发布