我正在尝试使用 TCP/IP 将文件从一台计算机传输到另一台计算机。我已经用java编写了代码,如下所示。但是,代码不起作用,在使用多个 catch 块后,我发现这是由于“SocketException”引起的。谁能告诉我如何解决这个问题?这是我的代码-
TCP客户端
import java.net.*;
导入 java.io。; 导入 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)
{
;
}
}
}
TCP服务器
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");
}
}
}