java套接字缓冲区和字符串
对于家庭作业,我尝试发送一个文件和一些与此文件对应的参数。 因此,我发送我的文件并在字符串之后发送。 问题是我的参数转到我的文件,而不是在我的变量中。我理解这个问题,只要他收到一些东西,我的循环就会继续在文件中写入,但我想停止它,并将我的参数从文件中移出 这里是我的代码客户端:java套接字缓冲区和字符串,java,sockets,buffer,Java,Sockets,Buffer,对于家庭作业,我尝试发送一个文件和一些与此文件对应的参数。 因此,我发送我的文件并在字符串之后发送。 问题是我的参数转到我的文件,而不是在我的变量中。我理解这个问题,只要他收到一些东西,我的循环就会继续在文件中写入,但我想停止它,并将我的参数从文件中移出 这里是我的代码客户端: public static void transfert(InputStream in, OutputStream out) throws IOException{ PrintWriter printOu
public static void transfert(InputStream in, OutputStream out) throws IOException{
PrintWriter printOut;
byte buf[] = new byte[1024];
int n;
while((n=in.read(buf))!=-1)
out.write(buf,0,n);
printOut = new PrintWriter(out);
printOut.println("add");
System.out.println("envoie !!!");
printOut.println("1");
printOut.println("3");
// out.write(getBytes("add"),0,0);
printOut.flush();
}
这里是我的服务器代码:
public static void transfert(InputStream in, OutputStream out, boolean closeOnExit) throws IOException
{
byte buf[] = new byte[1024];
int n;
while((n=in.read(buf))!=-1)
out.write(buf,0,n);
buffIn = new BufferedReader (new InputStreamReader(in));
String nom_methode = buffIn.readLine();
String param1 = buffIn.readLine();
String param2 = buffIn.readLine();
System.out.println("methode:"+nom_methode+"param1:"+param1+"param2:"+param2);
if (closeOnExit)
{
in.close();
out.close();
}
}
编辑:
我仍然错过了一些东西,现在我的线程有一个错误,我想问题在于我的循环在输入中读取了我的文件。
而且,实际上param仍然在我的文件中,而不是在我的param中。。。为什么循环在EOF后不停止
错误:
Exception in thread "Thread-0" java.lang.IndexOutOfBoundsException
at java.io.FileOutputStream.writeBytes(Native Method)
at java.io.FileOutputStream.write(FileOutputStream.java:318)
at serveurthread.AcceptClient.transfert(AcceptClient.java:45)
at serveurthread.AcceptClient.run(AcceptClient.java:84)
at java.lang.Thread.run(Thread.java:722)
client:
public static void transfert(InputStream in, OutputStream out) throws IOException{
PrintWriter printOut;
printOut = new PrintWriter(out);
byte buf[] = new byte[1024];
int n;
while((n=in.read(buf))!=-1)
out.write(buf,0,n);
printOut.print('\u0004');
printOut.flush();
printOut.println("add");
System.out.println("envoie !!!");
printOut.println("1");
printOut.println("3");
// out.write(getBytes("add"),0,0);
printOut.flush();
}
服务器:
public static void transfert(InputStream in, OutputStream out, boolean closeOnExit) throws IOException
{
byte buf[] = new byte[1024];
int n;
while((n=in.read(buf))!= (int)'\u0004'){
out.write(buf,0,n);
}
buffIn = new BufferedReader (new InputStreamReader(in));
String nom_methode = buffIn.readLine();
String param1 = buffIn.readLine();
String param2 = buffIn.readLine();
System.out.println("methode:"+nom_methode+"param1:"+param1+"param2:"+param2);
if (closeOnExit)
{
in.close();
out.close();
}
}
您需要在流中使用某种表示文件结束的标记。我建议使用
'\u0004'
这是EOF字符。基本上,在写入文件后写入此字符,然后在服务器中调整循环,如下所示:
while((n=in.read(buf))!=(int)'\u0004')
out.write(buf,0,n);
现在,服务器在必要时停止读取文件,然后可以开始读取字符串
另外,
read
返回读取的字节数,而不是字符数。我将通过声明字节而不是字节数组一次传递一个字节。read(byte[])返回一个计数,而不是流中的一个字符-1我最终通过字符串发送所有内容,并在服务器中将字符串文件更改为字节。