【发布时间】:2017-02-20 20:54:26
【问题描述】:
我正在尝试制作简单的服务器客户端应用程序,让客户端向服务器发送文件,然后服务器发送确认消息,表明它收到了文件
这是服务器类。
public class Server {
public static void main(String[] args) {
try {
ServerSocket server=new ServerSocket(9090);
while(true){
Socket clientSocket=server.accept();
ClientThread client=new ClientThread(clientSocket);
client.start();
}
} catch (IOException e) {
System.out.println(e.toString());
}
}
}
ClientThread 类
public class ClientThread extends Thread {
private Socket socket;// socket to connect through
private BufferedInputStream SocketInput;// stream to read from socket
private BufferedOutputStream FileOutput;// stream to write file through it
private PrintWriter SocketOutput; // print writer to write through socket
public ClientThread(Socket socket){// constructor
this.socket=socket;
}
public void run(){
try {
//get socket input stream
SocketInput=new BufferedInputStream(socket.getInputStream());
//get socket output stream
SocketOutput=new PrintWriter(socket.getOutputStream(),true);
// get the file from client
int NBytes=0;
byte[] data=new byte[1024];
FileOutput=new BufferedOutputStream(new FileOutputStream("C:/Users/mohamed/Desktop/Download/band.jpg"));
while((NBytes=SocketInput.read(data))!=-1){
FileOutput.write(data,0,NBytes);
FileOutput.flush();
}
// send ack. that file has been received
SocketOutput.println("File has been sent sucessfully");
//close all streams
FileOutput.close();
SocketInput.close();
SocketOutput.close();
socket.close();
}
catch (IOException e) {
System.out.println(e.toString());
}
}
}
客户端类
public class Client {
public static void main(String[] args) {
// file will be sent
File f=new File("D:/images/band.jpg");
try {
// get address of local host
InetAddress serverAddress=InetAddress.getLocalHost();
//create socket
Socket socket=new Socket(serverAddress,9090);
// create streams
BufferedInputStream input=new BufferedInputStream(new FileInputStream(f));
BufferedOutputStream output=new BufferedOutputStream(socket.getOutputStream());
BufferedReader p=new BufferedReader(new InputStreamReader(socket.getInputStream()));
// send the file
byte[] data=new byte[1024];
int Nbytes=0;
while((Nbytes=input.read(data))!=-1){
output.write(data,0,Nbytes);
output.flush();
}
// read the ack. and print it
System.out.println(p.readLine());
//close streams & socket
p.close();
input.close();
output.close();
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
当我运行服务器和客户端时我得到了什么错了,有什么问题?
【问题讨论】: