我试图从客户端向服务器发送文件。服务器接收文件,然后向客户端发送确认消息。发送文件,然后通过套接字发送消息
我的问题是客户端在等待确认时变得无响应。
服务器:
import java.net.*;
import java.io.*;
public class Server {
public static void main(String args[]) throws IOException {
int port = 1234;
ServerSocket server_socket;
server_socket = new ServerSocket(port);
System.out.println("Server waiting for client on port "
+ server_socket.getLocalPort());
// server infinite loop
while (true) {
Socket socket = server_socket.accept();
System.out.println("New connection accepted "
+ socket.getInetAddress() + ":" + socket.getPort());
try {
byte[] b = new byte[1024];
int len = 0;
int bytcount = 1024;
String FileName = "C:\\test\\java\\tmp\\sentfile.pdf";
FileOutputStream inFile = new FileOutputStream(FileName);
InputStream is = socket.getInputStream();
BufferedInputStream in2 = new BufferedInputStream(is, 1024);
while ((len = in2.read(b, 0, 1024)) != -1) {
bytcount = bytcount + 1024;
inFile.write(b, 0, len);
}
System.out.println("Bytes Writen : " + bytcount);
//Sending the response back to the client.
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.flush();
oos.writeObject("ok");
System.out.println("Message sent to the client is "+"ok");
in2.close();
inFile.close();
} catch (IOException e) {
System.out.println("Unable to open file" + e);
return;
}
socket.close();
System.out.println("Connection closed by client");
}
}
}
客户:
import java.net.*;
import java.io.*;
public class Client {
public static void main(String[] args) throws UnknownHostException,
IOException, ClassNotFoundException {
int port = 1234;
Socket socket = null;
// connect to server
socket = new Socket("127.0.0.1", port);
try {
byte[] buf = new byte[1024];
OutputStream os = socket.getOutputStream();
BufferedOutputStream out = new BufferedOutputStream(os, 1024);
String file = "C:\\test\\java\\client\\source.pdf";
FileInputStream in = new FileInputStream(file);
int i = 0;
int bytecount = 1024;
while ((i = in.read(buf, 0, 1024)) != -1) {
bytecount = bytecount + 1024;
out.write(buf, 0, i);
out.flush();
}
System.out.println("Bytes Sent :" + bytecount);
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
String confirmation = (String) ois.readObject();
System.out.println("from server : " + confirmation);
out.close();
in.close();
} catch (IOException e) {
System.out.println(e);
}
socket.close();
}
}
可能你不会从服务器端刷新输出流吗?你看到这条消息:'发送给客户端的消息是否可以'? – Lynch
将对无响应部分发表评论。如果客户端正在等待响应(阅读响应),那么我想它会没有响应。您是否考虑过在单独的线程中提出请求?在客户端的 – Andreas
,它在“Bytes Sent:..”之后被阻塞。 如果我评论第一部分,它是工作。 如果我对第二部分发表评论,它正在工作。 两者都不行。 – ophelie88