[英]Concurrency Issue Using Multithreading in Java
我已经用Java为服务器和客户端编写了代码。 客户端能够从服务器下载文件,并且服务器也应该能够同时向客户端提供文件。 为此,我在服务器中使用了多线程。
对于一个客户端,它工作得很好,但是在为每个客户端使用线程时,在我的代码中似乎无法正常工作。
由于未正确下载文件,这些文件已损坏并且对于不同的客户端来说大小不同。
从客户端接受后,我正在创建一个新的线程来为其提供服务器代码文件-
public static void send(String pathname) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException
{
try
{
System.out.println("....");
byte[] buf = new byte[1024];
OutputStream os = sock.getOutputStream();
//PrintWriter writer = new PrintWriter(os);
System.out.println("...11.");
BufferedOutputStream out = new BufferedOutputStream(os, 1024);
int i=0;
System.out.println("hi1");
File fp = new File(pathname);
System.out.println("hi2");
RandomAccessFile ra = new RandomAccessFile(fp,"r");
System.out.println("hi3");
long bytecount=1024;
////////////////
while((i=ra.read(buf, 0, 1024)) != -1)
{
System.out.println("hi");
bytecount += 1024;
System.out.println("hi6");
out.write(buf, 0, i);
System.out.println("hi7");
out.flush();
}
System.out.println("bye");
//os.flush();
//out.close();
ra.close();
//sock.close();
}
catch(IOException ex)
{
}
}
客户端用于文件接收的代码是
public void run() {
try{
byte[] b = new byte[1024];
int len = 0;
long bytcount = 1024;
File fp = new File(path);
RandomAccessFile ra=new RandomAccessFile(fp,"rw");
ra.seek(0);
InputStream is = sock.getInputStream();
BufferedReader reader=new BufferedReader(new InputStreamReader(is));
while ((len = is.read(b, 0, 1024)) != -1) {
bytcount = bytcount + 1024;
//decrypt
ra.write(b, 0, len);
}
//is.close();
//ra.close();
//sock.close();
}
catch(IOException ex){
ex.printStackTrace();
}
// throw new UnsupportedOperationException("Not supported yet.");
}
}
我没有弄明白这里出了什么问题。 请提前帮助很多thanx
send
是静态的,这向我建议您只有一个套接字,名为sock
,否则以下内容将无法编译。
public static void send(String pathname) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException
{
try
{
System.out.println("....");
byte[] buf = new byte[1024];
OutputStream os = sock.getOutputStream();
//PrintWriter writer = new PrintWriter(os);
System.out.println("...11.");
在这种情况下,很难看到交付给> 1个客户端的可靠性如何。 您一定会为每个客户端需要一个套接字来执行并发交付吗? 需要更多代码来确保这一点,但是看来套接字处理的设计可能需要修改。
您的第一个问题是您在服务器上使用OutputStream,在客户端上使用Reader。 客户端应该使用InputStreams,而不是Readers。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.