所以..我有一个服务器套接字,在这里:
ServerSocket server = new ServerSocket(5000);
while(true){
Socket cliente = server.accept();
Thread thread = new Thread(new Converter(cliente));
thread.start();
我的应用将Word文档(.doc
)转换为PDF。首先,我的服务器在收到.pdf归档后收到.doc,进行转换。
如何让客户端等待响应?
答案 0 :(得分:2)
如果我理解正确,那么每个接受的套接字(因此客户端)都会创建一个线程。此Converter
线程可以访问客户端套接字(每个客户端都有accept()
返回的不同套接字)。现在解决方案非常简单:
public void run() {
cliente.getInputStream(); //read .doc first
//do the conversion to .pdf
cliente.getOutputStream(); //send .pdf back
}
答案 1 :(得分:1)
得到:
private void getDocArchive(){
try {
InputStream in = socket.getInputStream();
BufferedInputStream buffer = new BufferedInputStream(in, 1024);
byte[] b = new byte[1024];
int len = 0;
int bytcount = 1024;
FileOutputStream out = new FileOutputStream("docs/atual.doc");
while ((len = buffer.read(b, 0, 1024)) != -1) {
bytcount = bytcount + 1024;
out.write(b, 0, len);
}
out.flush();
//out.close();
//buffer.close();
} catch (IOException e) {
System.out.println("Ocorreu um erro no recebimento do arquivo");
}
}
响应:
private void reponse() {
try {
OutputStream out = socket.getOutputStream();
InputStream in = new FileInputStream(pdf);
BufferedInputStream buffer = new BufferedInputStream(in, 1024);
byte[] b = new byte[1024];
int len = 0;
int bytcount = 1024;
int i = 0;
while ((len = buffer.read(b, 0, 1024)) != -1) {
bytcount = bytcount + 1024;
out.write(b, 0, len);
}
out.flush();
out.close();
buffer.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
}
我的客户:
public static void main(String[] args) throws Exception {
try {
Socket client = new Socket("127.0.0.1", 5000);
OutputStream out = client.getOutputStream();
InputStream in = new FileInputStream("C:\\autistmo.docx");
BufferedInputStream buffer = new BufferedInputStream(in, 1024);
byte[] b = new byte[1024];
int len = 0;
int bytcount = 1024;
while ((len = buffer.read(b, 0, 1024)) != -1) {
bytcount = bytcount + 1024;
out.write(b, 0, len);
}
// resposta
BufferedInputStream buffer2 = new BufferedInputStream(in, 1024);
FileOutputStream out2 = new FileOutputStream("docs/final.doc");
while ((len = buffer2.read(b, 0, 1024)) != -1) {
bytcount = bytcount + 1024;
out2.write(b, 0, len);
}
out2.close();
buffer2.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
运行方法:
@Override
public void run() {
getDocArchive();
converter();
reponse();
}