欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-12-14 09:38:46
本文实例讲述了java基于socket传输zip文件的方法。分享给大家供大家参考,具体如下: 服务器端程序: import java.io.*; import...

本文实例讲述了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程序设计有所帮助。

上一篇:

下一篇: