欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

java基于socket传输zip文件功能示例

时间:2021-07-19 07:59:08|栏目:JAVA代码|点击:

本文实例讲述了java基于socket传输zip文件的方法。分享给大家供大家参考,具体如下:

服务器端程序:

import java.io.*;
import java.net.*;
import java.io.BufferedInputStream;
public class SocketServer {
ServerSocket ss=null;
Socket s=null;
DataInputStream inStream=null;
DataOutputStream outStream=null;
FileInputStream fin = null;
public SocketServer() {
 try{
  ss=new ServerSocket(765);
  s.setSoTimeout(3000);
 }catch(Exception e){
  System.out.println(e.toString());
 }
}
void waitForClient(){
 try{
 while(true){
 s=ss.accept();
 ThreadServer thread = new ThreadServer(s);
 thread.start();
 }
 }catch(Exception e){
  System.out.println(e.toString());
 }
}
public static void main(String[] args) {
SocketServer socketServer1 = new SocketServer();
socketServer1.waitForClient();
}
}

线程类:

import java.io.*;
import java.net.*;
class ThreadServer extends Thread{
 private Socket socket;
 private DataInputStream inStream=null;
 private DataOutputStream outStream=null;
 private FileInputStream fin = null;
 public ThreadServer(Socket sock){
  this.socket = sock;
 }
 public void run(){
 boolean bool = false;
 //while(!bool){
 try{
 inStream=new DataInputStream(socket.getInputStream());
 outStream=new DataOutputStream(socket.getOutputStream());
 fin = new FileInputStream("C:/temp/socket/200212060001_ds.zip");
 //socket.setSoTimeout(3000);
 byte[] b = new byte[200];
 int i;
 while((i=fin.read(b))!=-1){
 outStream.write(b);
 }
 fin.close();
 socket.close();
 //bool = true;
 }catch(IOException ex){
 System.out.println(ex);
 }
 //}
 }
}

客户端:

import java.net.*;
import java.io.*;
public class SocketClient{
Socket s=null;
DataInputStream inStream=null;
DataOutputStream outStream=null;
FileOutputStream fout = null;
public SocketClient() {
try{
s=new Socket("192.9.207.52",765); //把这里的IP改成你运行SocketServer.class的IP
inStream=new DataInputStream(s.getInputStream());
outStream=new DataOutputStream(s.getOutputStream());
fout = new FileOutputStream("C:/temp/socket/test11.zip");
s.setSoTimeout(3000);
waitData();
}
catch(Exception e){
System.out.println(e.toString());
}
}
void init() throws Exception{
}
void waitData(){
try{
 byte[] b = new byte[200];
 int i;
 while((i=inStream.read(b))!=-1){
  fout.write(b);
 }
 fout.flush();
 fout.close();
 s.close();
}catch(Exception e){
System.out.println(e.toString());
}
}
public static void main(String[] args) {
SocketClient socketClient1 = new SocketClient();
}
}

更多关于java相关内容感兴趣的读者可查看本站专题:《Java Socket编程技巧总结》、《Java文件与目录操作技巧汇总》、《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》和《Java缓存操作技巧汇总

希望本文所述对大家java程序设计有所帮助。

上一篇:springboot如何读取application.yml文件

栏    目:JAVA代码

下一篇:Java使用代理进行网络连接方法示例

本文标题:java基于socket传输zip文件功能示例

本文地址:http://www.codeinn.net/misctech/159001.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有