Java 网络编程

最近在学网络编程的时候 发现 用客户端 给服务器端 传 的MP3文件 居然不能播放。。而且 原本是 40.9M的 传完后后变为了 43M 。。呵呵是奇怪 请各位大虾 给点指点!

服务器端
import java.io.*;
import java.net.*;

public class Sendserver {
public static void main(String[] args) throws IOException {
ServerSocket s = new ServerSocket(9999);

while (true){
Socket d= s.accept();
System.out.println("客户端连接成功");

DataInputStream dis = new DataInputStream(d.getInputStream());

int b = 0;

BufferedWriter bw = new BufferedWriter(new FileWriter("G:\\Track 01.mp3"));

while((b=dis.read())!=-1){
bw.write(b);
}
bw.flush();
bw.close();
dis.close();
System.out.println("传送完毕");
}

}
客户端

import java.io.*;
import java.net.*;

public class sendclient {
public static void main(String[] args) throws UnknownHostException, IOException{
Socket f= new Socket("127.0.0.1",9999);

try{
FileInputStream cc= new FileInputStream("D:\\Track 01.mp3");
BufferedInputStream bis = new BufferedInputStream(cc);
OutputStream out=f.getOutputStream();
DataOutputStream dos = new DataOutputStream(out);
BufferedOutputStream xie = new BufferedOutputStream(dos);

int b=0;
while((b=bis.read())!=-1){

xie.write(b);
}
xie.flush();

out.close();
bis.close();
}catch (IOException e){ }

}

}

import java.io.*;
import java.net.*;

public class Sendserver
{
public static int port = 3333;
public static void main(String[] args) throws IOException
{
ServerSocket s = new ServerSocket(port);
Socket d= s.accept();
System.out.println("客户端连接成功");

DataInputStream input = new DataInputStream(d.getInputStream());
int bufferSize = 8192;
byte[] buf = new byte[bufferSize];
DataOutputStream fileOut = new DataOutputStream(new BufferedOutputStream(
new BufferedOutputStream(new FileOutputStream(
"2.mp3"))));
while (true)
{
int read = 0;
if (input != null)
read = input.read(buf);

if (read == -1)
break;

byte[] temp=new byte[read];
for(int i=0;i<read;i++)
temp[i]=buf[i];
fileOut.write(temp);
}
fileOut.close();
System.out.println("传送完毕");

}
}

import java.io.*;
import java.net.*;

public class SendClient
{

public static void main(String[] args) throws UnknownHostException, IOException
{
try{
DataInputStream iinput = new DataInputStream(new BufferedInputStream(
new FileInputStream("1.mp3")));

InetAddress addr = InetAddress.getByName("localhost");
Socket f= new Socket(addr,3333);
OutputStream output=f.getOutputStream();

int bufferSize = 8192;
byte[] buf = new byte[bufferSize];
while (true)
{
int read = 0;
if (iinput != null)
read = iinput.read(buf);

if (read == -1)
break;

byte[] temp=new byte[read];
for(int i=0;i<read;i++)
temp[i]=buf[i];
output.write(temp);
output.flush();
}

iinput.close();
output.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

改动相当大,你自己看看吧。
温馨提示:内容为网友见解,仅供参考
第1个回答  2010-04-07
读到的数据;别放在字节数组里..全部放到集合里..我遇到过这种情况是因为数据传输过程中的丢失造成的;有时候比原文件大;有时候小..
第2个回答  2010-04-07
你这代码能编译过去啊???
Sendserver类的
while((b=dis.read())!=-1){
bw.write(b);
}
这不是这么用的啊!!
dis.read()后面肯定有个参数,用来接收输入的嘛。前面的返回值是写入了多少个字节的意思……
得改改代码。
后面的客户端的也是错的。
相似回答