[英]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.