各位高手如何利用socket实现客户机和服务机传送文件

haozb 2003-06-03 04:39:45
请问各位高手如何在利用socket实现客户机和服务机传送文件(包括各种扩展名文件),并能给出代码,谢谢!!!
...全文
64 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
ytdmm 2003-06-03
  • 打赏
  • 举报
回复
部分代码作为参考~~~~~~
服务器端:
try{
FileInputStream inputfile=
new FileInputStream(filename);
DataInputStream inputdata=
new DataInputStream(inputfile);
OutputStream output=connection.getOutputStream();
String buffer=new String();
byte data[]=new byte[500];
int nbyteread,length=0;
byte newData[]=new byte[500]; //直接用字节读取并传送
while((nbyteread=inputdata.read(data))!=-1){ //read file
for(int i=0; i<nbyteread; i++){
newData[length++]=data[i]; //读取字节
}
buffer=buffer+new String(data,0,nbyteread);
}
output.write(newData,0,newData.length); //直接发送
inputfile.close();
inputdata.close();
}
catch(IOException ie){
}
客户端:
try{
FileOutputStream outputfile=
new FileOutputStream(filename);
DataOutputStream outputdata=
new DataOutputStream(outputfile);
InputStream input=connection.getInputStream();
String buffer=new String(); //receive file to String
char c;
byte data[]=new byte[500];
int nbyteread;
byte newData[]=new byte[500]; //直接读取并存储
while(input.available()!=0){ //via input.available
nbyteread=input.read(data);
for(int i=0; i<nbyteread; i++){ //读取
newData[newData.length]=data[i];
}
buffer=buffer+new String(data,0,nbyteread);
}
outputdata.write(newData,0,newData.length);
outputfile.close();
outputdata.close();
}
catch(IOException ie){
}
hoxisoft 2003-06-03
  • 打赏
  • 举报
回复
用BufferedReader 和PrintStream类,直接传送字节数组

23,407

社区成员

发帖
与我相关
我的任务
社区描述
Java 非技术区
社区管理员
  • 非技术区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧