1 / 1 / 0
Регистрация: 10.04.2016
Сообщений: 7
|
16.03.2018, 16:46
|
7
|
Вопрос решен. Привожу код для тех кто столкнулся с подобной проблемой
Если на ваш счет код корявый сильно не ругать
Сервер:
Java | 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
| import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
*
* @author nomid
*/
public class Server {
public String HOST;
public int PORT;
ServerHandler SRVHAND = new ServerHandler();
public Server(String host, int port) {
this.HOST = host;
this.PORT = port;
}
public void run() throws InterruptedException, IOException {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap()
.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline().addLast(
new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()),
new StringDecoder(),
new StringEncoder(),
new ServerHandler()
);
}
});
bootstrap.bind(HOST, PORT).sync().channel();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while (true) {
SRVHAND.send(in.readLine());
}
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws InterruptedException, IOException {
new Server("127.0.0.1", 10101).run();
}
} |
|
Обработчик на сервере:
Java | 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
| import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.DefaultEventExecutor;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
/**
*
* @author nomid
*/
public class ServerHandler extends SimpleChannelInboundHandler<String>{
private static final ChannelGroup CHANNELS = new DefaultChannelGroup(new DefaultEventExecutor());
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
Channel incoming = ctx.channel();
incoming.writeAndFlush("[SERVER] - Wilcom to chat!\r\n");
for (Channel channel : CHANNELS) {
channel.writeAndFlush("[" + incoming.remoteAddress() + "] has joined!\r\n");
}
CHANNELS.add(incoming);
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
Channel removed = ctx.channel();
for (Channel channel : CHANNELS) {
channel.write("[" + removed.remoteAddress() + "] has remover chat!\r\n");
channel.flush();
channel.writeAndFlush(ctx);
}
CHANNELS.remove(removed);
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
Channel talk = ctx.channel();
System.out.println("channelRead0 [" + talk.remoteAddress() + "] " + msg);
for (Channel channel : CHANNELS) {
if (channel.remoteAddress() != talk.remoteAddress()){
channel.writeAndFlush("[" + talk.remoteAddress() + "] " + msg + "\r\n");
} else {
channel.writeAndFlush("[yuo] " + msg + "\r\n");
}
}
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
Channel talk = ctx.channel();
String str_msg = msg.toString();
System.out.println(str_msg);
String sd = "";
if ((str_msg.charAt(0) == '[') && (str_msg.charAt(str_msg.length() - 1) == ']')) {
//Определение имени файла для записи
String[] strname = talk.remoteAddress().toString()
.replace('/', ' ').replace(':', ' ')
.trim().split(" ");
String nameFile = "C:\\Users\\nomid\\Desktop\\Transfer\\out_file\\"
+ strname[0] + " copy.txt";
//Подготовка данных для записи в файл
String[] str = msg.toString().replace("[", " ").replace("]", " ").trim().split(", ");
System.out.println("channelRead [" + talk.remoteAddress() + "] ");
System.out.println(nameFile);
File dest;
FileOutputStream fileOS;
FileWriter fw;
// OutputStreamWriter outSW = new OutputStreamWriter(fileOS, "windows-1251");
//Создание файла, если он не существует
if (!new File(nameFile).exists()){
System.out.println(new File(nameFile).exists());
dest = new File(nameFile);
fileOS = new FileOutputStream(dest);
}
//Запись в файл
for (int i = 0; i < str.length; i++) {
//Перевод числового значения символа в символ
char c = (char) Integer.parseInt(String.valueOf(Integer.parseInt(str[i])));
System.out.print(c);
sd += c;
// outSW.append(c);
}
Files.write(Paths.get(nameFile), sd.getBytes(), StandardOpenOption.APPEND);
// outSW.close();
System.out.println("");
talk(ctx, sd);
} else {
System.out.println("channelRead [" + talk.remoteAddress() + "] " + msg);
talk(ctx, msg);
}
}
public void talk(ChannelHandlerContext ctx, Object msg) {
Channel talk = ctx.channel();
for (Channel channel : CHANNELS) {
if (channel.remoteAddress() != talk.remoteAddress()){
channel.writeAndFlush("[" + talk.remoteAddress() + "] " + msg + "\r\n");
} else {
channel.writeAndFlush("[yuo] " + msg + "\r\n");
}
}
}
public void send(String msg) {
for (Channel channel : CHANNELS) {
channel.writeAndFlush("[SERVER] " + msg + "\r\n");
}
}
} |
|
Клиент:
Java | 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
| import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFileChooser;
/**
*
* @author nomid
*/
public class Client {
public String HOST;
public int PORT;
Channel CHANNEL;
public Client(String host, int port) {
this.HOST = host;
this.PORT = port;
}
public void run() throws InterruptedException, IOException {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap()
.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline().addLast(
new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()),
new StringDecoder(),
new StringEncoder(),
new ClientHandler());
}
});
CHANNEL = bootstrap.connect(HOST, PORT).sync().channel();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String str = in.readLine();
if (!"file".equals(str)) {
CHANNEL.writeAndFlush(str + "\n");
} else {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("C:\\Users\\nomid\\Desktop\\Transfer\\out_file"));
int send = chooser.showDialog(null, "Send");
if (send == JFileChooser.APPROVE_OPTION) {
sendFile(this.CHANNEL, chooser.getSelectedFile().getPath());
CHANNEL.writeAndFlush(chooser.getSelectedFile().getPath() + "\n");
}
}
}
} finally {
group.shutdownGracefully();
}
}
public static void main(String[] args) throws InterruptedException, IOException {
new Client("127.0.0.1", 10101).run();
}
private void sendFile(Channel channel, String path) {
try {
//Чтение файла
File source = new File(path);
FileInputStream fileIS = new FileInputStream(source);
InputStreamReader inputSR = new InputStreamReader(fileIS, "windows-1251");
String namestr = source.getName();
String[] newfilename = namestr.split(".txt");
//Запись в файл
File dest = new File(source.getParent() + "\\" + newfilename[0] + " copy.txt");
FileOutputStream fileOS = new FileOutputStream(dest);
OutputStreamWriter outSW = new OutputStreamWriter(fileOS, "windows-1251");
System.out.println(source.length() + " байт");
int c;
List<Integer> out = new ArrayList();
//Передача файла
while ((c = inputSR.read()) != -1) {
int integer= c;
outSW.append((char) integer);
if (c != 10) {
out.add(c);
} else {
out.add(c);
channel.writeAndFlush(out + "\n");
out.clear();
}
}
out.clear();
inputSR.close();
outSW.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
} |
|
Обработчик на клиенте:
Java | 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
| import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
/**
*
* @author nomid
*/
public class ClientHandler extends SimpleChannelInboundHandler<String>{
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println(msg);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println(msg);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
} |
|
1
|