我正在嘗試使用TCP/IP將文件從一臺計算機傳輸到另一臺計算機。我已經用java編寫了代碼,如下所示。但是,代碼不起作用,並且在使用多個catch塊之後,我發現這是由於'SocketException'造成的。誰能告訴我如何解決這個問題?這裏是我的代碼 -Java中的SocketException:通過TCP/IP傳輸文件
的TcpClient
import java.net.*;
進口java.io. ; import java.util。;
公共類的TcpClient {
public static void main (String args[])
{
try
{
Socket sock = new Socket("localhost", 6839);
InputStream is = null;
FileOutputStream out = null;
boolean doesntexist=false;
String filename = "D:\\"+"Test"+".pdf";
System.out.println("Here!");
File newplaylist = new File(filename);
doesntexist = newplaylist.createNewFile();
if(!doesntexist)
{
newplaylist.delete();
newplaylist.createNewFile();
}
byte[] mybytearray = new byte[1024];
is = sock.getInputStream();
// Create a new file output stream.
out = new FileOutputStream(newplaylist);
int count;
while ((count = is.read(mybytearray)) >= 0) {
out.write(mybytearray, 0, count);
}
out.close();
is.close();
sock.close();
}
catch(SocketException e)
{
System.out.println("Socket exception");
}
catch(ProtocolException e)
{
System.out.println("Protocol exception");
}
catch(IOException ds)
{
;
}
}
}
TCPSERVER
import java.util.*;
import java.io.*;
import java.net.*;
import java.nio.channels.*;
class Fileserver
{
public static void main(String args[]) throws IOException
{
ServerSocket server = new ServerSocket(6839);
File myFile = new File("E:\\file1.pdf");
FileInputStream file = null;
OutputStream os = null;
Socket sock=null;
sock = server.accept();
try
{
byte[] mybytearray = new byte[1024];
file = new FileInputStream(myFile);
os = sock.getOutputStream();
int count;
while ((count = file.read(mybytearray)) >= 0) {
os.write(mybytearray, 0, count);
}
os.flush();
}
catch(IOException e)
{
System.out.println("No file");
}
catch(IllegalBlockingModeException ea)
{
System.out.println("blah!");
}
finally
{
System.out.println("hello");
file.close();
os.close();
sock.close();
System.out.println("Socket closed");
}
}
}
請勿編寫自己的錯誤消息。使用例外中的那個。*從不*忽略IOException。 – EJP