Как с помощью NIO сделать многопользовательский сервер который посылает файл или коллекцию, а клиенты его принимают.
Нашёл рабочий пример обратного процесса то есть клиенты посылают на сервер файл. Можно ли переделать вот этот код?(сам пытался и у меня не получилось) Где можно почитать про NIO нагуглил скромные статейки в которых почти нечего не описано.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
package ru.shapovalov;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Created by igor on 22.01.15.
*/
public class Server implements Runnable{
private Selector sel;
@Override
public void run() {
try {
ServerSocketChannel channel = ServerSocketChannel.open();
channel.configureBlocking(false);
channel.bind(new InetSocketAddress(1999));
sel = Selector.open();
channel.register(sel, SelectionKey.OP_ACCEPT);
while (true) {
if (sel.isOpen()) {
int keys = sel.select();
if (keys > 0) {
Set<SelectionKey> selectedKeys = sel.selectedKeys();
Iterator<SelectionKey> iterator = selectedKeys.iterator();
while (iterator.hasNext()) {
SelectionKey sk = iterator.next();
if (sk.isValid() && sk.isAcceptable()) {
accept(sk);
}
if (sk.isValid() && sk.isReadable()) {
read(sk);
}
if (sk.isValid() && sk.isWritable()) {
}
}
selectedKeys.clear();
}
}
}
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void read(SelectionKey key) {
SocketChannel channel = (SocketChannel) key.channel();
ByteBuffer buff = ByteBuffer.allocate(8192);
File f = new File("file");
try (FileChannel fileChannel = new FileOutputStream(f, true).getChannel()) {
int read;
int totalRead = 0;
while ((read = channel.read(buff)) > 0) {
System.out.println("current read: " + read);
totalRead += read;
buff.flip();
fileChannel.write(buff);
buff.clear();
}
System.out.println("total server read: " + totalRead);
} catch (IOException ex) {
try {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
key.cancel();
channel.close();
} catch (IOException ex1) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex1);
}
}
}
private void accept(SelectionKey key) {
try {
ServerSocketChannel channel = (ServerSocketChannel) key.channel();
SocketChannel acceptedClient = channel.accept();
acceptedClient.configureBlocking(false);
acceptedClient.register(sel, SelectionKey.OP_READ);
//sel.wakeup();
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
package ru.shapovalov;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Created by igor on 22.01.15.
*/
public class Client implements Runnable{
@Override
public void run() {
try {
SocketChannel channel = SocketChannel.open();
channel.configureBlocking(false);
channel.connect(new InetSocketAddress("localhost", 1999));
Selector sel = Selector.open();
channel.register(sel, SelectionKey.OP_CONNECT);
while (true) {
if (sel.isOpen()) {
int keys = sel.select();
if (keys > 0) {
Set<SelectionKey> selectedKeys = sel.selectedKeys();
for (SelectionKey sk : selectedKeys) {
if (!sk.isValid()) {
break;
}
if (sk.isConnectable()) {
System.out.println("accepting");
channel.finishConnect();
channel.register(sel, SelectionKey.OP_WRITE);
sk.interestOps(SelectionKey.OP_WRITE);
}
if (sk.isWritable()) {
SocketChannel ch = (SocketChannel) sk.channel();
System.out.println("writing");
FileChannel fileChannel = new FileInputStream(new File("/home/igor/TaskManagerClient.jar")).getChannel();
ByteBuffer buffer = ByteBuffer.allocate(8192);
int bytes;
buffer.clear();
int total = 0;
while ((bytes = fileChannel.read(buffer)) > 0) {
total += bytes;
buffer.flip();
System.out.println("wrote " + bytes + " bytes");
ch.write(buffer);
buffer.clear();
}
System.out.println("total wrote: " + total);
//sk.interestOps(SelectionKey.OP_READ);
}
}
}
}
}
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
}