Java的Socket编程例子

本文介绍了一种使用Java实现的图片上传客户端与多线程接收图片的服务器端代码。客户端通过Socket连接到服务器,并将指定路径的图片文件发送至服务器。服务器采用多线程方式接收并保存图片,同时反馈接收状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


//上传图片客户端代码
public class UploadImgClientDemo {

public static void main(String[] args) throws UnknownHostException, IOException {
                //创建socket对象
Socket socket=new Socket("192.168.1.104",12345);

BufferedInputStream bis=new BufferedInputStream

                (new FileInputStream("H:\\Copy\\M\\facebook\\Zack3\\smalls.jpg"));

BufferedOutputStream bos=new BufferedOutputStream(socket.getOutputStream());

byte[] bys=new byte[1024];
int len=0;
while((len=bis.read(bys))!=-1){
bos.write(bys, 0, len);
}
bos.flush();
socket.shutdownOutput();
InputStream in=socket.getInputStream();
len=in.read(bys);
String s=new String(bys,0,len);
System.out.println(s);

bis.close();
socket.close();

}

}


//多线程接收图片服务器端代码
public class UploadImgServerDemo {

public static void main(String[] args) throws IOException {
ServerSocket server=new ServerSocket(12345);

while(true){
Socket s=server.accept();
new Thread(new SocketThread(s)).start();
}
}

}

//多线程对象

public class SocketThread implements Runnable {
public static int i;
private Socket s;
public SocketThread(Socket s){
this.s=s;
}
@Override
public void run() {
BufferedOutputStream bos=null;
try {
BufferedInputStream bis=new BufferedInputStream(s.getInputStream());
String name=getName();
bos=new BufferedOutputStream(new FileOutputStream(name));
byte[] bys=new byte[1024];
int len=0;
while((len=bis.read(bys))!=-1){
bos.write(bys, 0, len);
}
bos.flush();
OutputStream out=s.getOutputStream();
bys="图片上传成功!".getBytes();
out.write(bys, 0, bys.length);

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{

try {
bos.close();
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private synchronized static String getName() {
i++;
return i+"small.jpg";
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值