ServerSocket网络编程之图片上传
本节代码具体讲述的是ServerSocket网络编程中,客户端上传图片到服务器的具体实现
废话不说,上代码
服务端
public class Server {
public static void main(String[] args) {
try {
// 此处设定服务器端口
ServerSocket server = new ServerSocket(8888);
System.out.println("服务器成功监听...");
// 服务器成功监听...
Socket socket = server.accept();
// 从管道获取资源
InputStream is = socket.getInputStream();
// 写入到服务器本地,具体地址可根据情况变化,此处操作暂时以 D 盘根目录演示
// 此地址只在Windows环境运行,若在liunx环境运行 "//" 符号请更换为 File.separator
FileOutputStream os = new FileOutputStream("D://aa.jpg");
// 读写操作
byte[] buf = new byte[1024 * 8];
int length;
while ((length = is.read(buf)) != -1) {
os.write(buf, 0, length);
}
// 关闭流
os.close();
is.close();
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
注释:此地址只在Windows环境运行,若在liunx环境运行 " // " 符号请更换为 File.separator
客户端
public class Client {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
// 此处为服务端的 IP 和端口,具体操作请以实际为准
Socket socket = new Socket("10.7.121.96", 8888);
System.out.println("请输入图片位置.....");
// 图片位置位于本人电脑绝对路径(例如:D:/a.jpg)
String path = sc.next();
// 获取本地图片
FileInputStream is = new FileInputStream(path);
// 写入到socket管道
OutputStream os = socket.getOutputStream();
// 读写操作
byte[] buf = new byte[1024 * 8];
int length;
while ((length = is.read(buf)) != -1) {
os.write(buf, 0, length);
}
// 提示结束
System.out.println("over");
// 关闭流
os.close();
is.close();
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
以上为客户端发送图片到服务端的全部代码,本人亲测可用,若有疑问,欢迎留言或者私信本人。若有不足之处,欢迎大家指定,不胜感激。