Java 网络编程

2025-04-25 09:41:46
推荐回答(3个)
回答1:

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 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 temp[i]=buf[i];
output.write(temp);
output.flush();
}

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

改动相当大,你自己看看吧。

回答2:

读到的数据;别放在字节数组里..全部放到集合里..我遇到过这种情况是因为数据传输过程中的丢失造成的;有时候比原文件大;有时候小..

回答3:

你这代码能编译过去啊???
Sendserver类的
while((b=dis.read())!=-1){
bw.write(b);
}
这不是这么用的啊!!
dis.read()后面肯定有个参数,用来接收输入的嘛。前面的返回值是写入了多少个字节的意思……
得改改代码。
后面的客户端的也是错的。