创建客户端连接服务端,获取服务端的反馈信息
客户端代码:
public class Client {
//客户端
public static void main(String[] args) {
try {
//1.创建对象,主动连接服务端
//本机:localhost 127.0.0.1 具体IP地址 port:本机端口号
Socket socket = new Socket("192.168.??.??",1234);
//Socket[addr=/192.168.2.9,port=8085,localport=6582]
System.out.println("socket=" + socket);
//2.数据交互 IO流
//客户端: 接收服务端发过来的内容 输入流
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
System.out.println(dataInputStream.readUTF());
} catch (IOException e) {
e.printStackTrace();
}
}
}
服务端代码:
public class Server {
public static void main(String[] args) {
try {
//1.创建对象,指定端口号
ServerSocket serverSocket = new ServerSocket(8085);
System.out.println("服务器已开启,监听8085端口");
//死循环
//2.等待客户端访问
Socket accept = serverSocket.accept();
System.out.println("已链接到客户端" + accept);
//192.168.2.9
System.out.println(accept.getInetAddress().getHostAddress());
//3.数据交互 IO
//服务端:向客户端发消息 输出流
DataOutputStream dataOutputStream = new DataOutputStream(accept.getOutputStream());
dataOutputStream.writeUTF("111");
} catch (IOException e) {
e.printStackTrace();
}
}
}
用来反馈给用户信息代码:
dataOutputStream.writeUTF("你好,客户端");
创建客户端传送给服务端文件:
客户端代码:
//客户端
public class Client {
public static void main(String[] args) {
//指定本地图片的路径
String localPath ="D:\\workspace\\two\\AnnotationPro\\src\\upload\\微信图片_20211215170905.png";
Socket socket = null;
try {
//1. 创建对象 指定IP地址和端口号
socket = new Socket("192.168.??.??", 8086);
//2.数据交互
//读取本地文件 输入流
BufferedInputStream inputStream = new BufferedInputStream(
new FileInputStream(
new File(localPath)));
//发送给服务端 输出流
BufferedOutputStream outputStream = new BufferedOutputStream(socket.getOutputStream());
//读写操作
int len;
while ((len=inputStream.read())!= -1){
outputStream.write(len);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
socket.shutdownOutput();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
服务端代码:
public class Server {
public static void main(String[] args) {
//服务端
//保存图片的途径
String imgPath = "D:\\workspace\\two\\AnnotationPro\\src\\upload\\up";
try {
//1.创建对象,指定端口
ServerSocket serverSocket = new ServerSocket(8086);
System.out.println("服务器已开启, 监听8086端口");
while (true){
//2.等待客户端连接
//阻塞
Socket accept = serverSocket.accept();
//获取Ip地址
String hostAddress = accept.getInetAddress().getHostAddress();
System.out.println("已连接上的客户端:" + hostAddress);
//3.数据交互 IO流
//接收客户端传过来的图片 输入流
BufferedInputStream bufferedInputStream = new BufferedInputStream(accept.getInputStream());
//把图片进行保存到指定位置 输出流
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
new FileOutputStream(new File(imgPath,hostAddress)));
//读写操作
int len;
while ((len=bufferedInputStream.read())!=-1){
bufferedOutputStream.write(len);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
在客户端传输文件时,不可以是字符串:
OK
NO
服务端被客户端连接运行:
客户端得到服务端得到反馈运行: