Форум программистов, компьютерный форум, киберфорум
Java: Сети
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.77/47: Рейтинг темы: голосов - 47, средняя оценка - 4.77
0 / 0 / 0
Регистрация: 17.08.2016
Сообщений: 9
1

Передача файлов через сокеты

17.09.2017, 10:29. Показов 8453. Ответов 6
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Всем привет.

Нужно передать файлы с клиента на сервер
передача в клиенте такая:
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public void loadFile(ActionEvent actionEvent) {
        try {
            FileChooser fileChooser = new FileChooser();
            fileChooser.setTitle(LOAD_FILE);
            File file = fileChooser.showOpenDialog(infoText.getScene().getWindow());
            String fileName = file.getName();
            DataOutputStream outFileName = new DataOutputStream(socket.getOutputStream());
            outFileName.writeUTF(fileName);
            FileInputStream in = new FileInputStream(file);
            OutputStream out = socket.getOutputStream();
            byte[] bt = new byte[1024];
            while ((in.read(bt)) > 0) {
                out.write(bt);
            }
//            out.close();
//            in.close();
//            outFileName.close();
            System.out.println("File transfer complete");
 
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
В сервере прием такой

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
private void connection() {
                while (true) {
                    try {
                        DataInputStream fileNameInfo = new DataInputStream(socket.getInputStream());
                        String fileName = fileNameInfo.readUTF();
                        InputStream in = socket.getInputStream();
                        FileOutputStream fOut = new FileOutputStream("D:\\Geek\\files\\" + fileName);
                        byte[] bt = new byte[1024];
                        while ((in.read(bt)) > 0) {
                            fOut.write(bt);
                        }
//                        fOut.close();
//                        in.close();
//                        fileNameInfo.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
когда в клиенте закоменчено закрытие исходящих потоков - то благополучно передается один файл. все последующие просто игнорятся без ошибок в консоле

если разкоментировать закрытие - то на второмм загружаемом файле выскакивает ошибка клиета soket close
хотя явно сркет нигде не закрывается
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
17.09.2017, 10:29
Ответы с готовыми решениями:

Передача файлов через сокеты
Есть сервер import java.io.DataOutputStream; import java.io.File; import...

Передача файлов через wifi
Здравствуйте! Задача состоит в том, чтобы передать файлы любого размера через wifi (с моего...

Сокеты: передача на несколько адресов
здравствуйте. мне нужно выполнить передачу нескольких объектов (чисел и массивов) с клиента на 3...

Опять сокеты и передача строк
Здравствуйте! Помогите разобраться в плане передачи текста с помощью сокетов. Соорудил простейшие...

6
Эксперт Java
378 / 370 / 114
Регистрация: 30.06.2010
Сообщений: 1,445
17.09.2017, 11:49 2
У тебя на сервере одно соединение только?

У тебя должен быть цикл с serverSocket.accept() и передачей только одного файла за соединение, а на клиенте каждый раз соединяешься, передаешь и закрываешь
0
0 / 0 / 0
Регистрация: 17.08.2016
Сообщений: 9
17.09.2017, 17:39  [ТС] 3
Спасибо, помогло!
Может есть более продвинутый способ передачи файлов по сети?
0
Эксперт Java
378 / 370 / 114
Регистрация: 30.06.2010
Сообщений: 1,445
17.09.2017, 18:05 4
А этот чем не устраивает?

Можешь использовать сервлеты или сразу spring. Гугли spring multipart file upload, на клиентской стороне будешь использовать RestTemplate
0
0 / 0 / 0
Регистрация: 17.08.2016
Сообщений: 9
18.09.2017, 07:21  [ТС] 5
тут будут проблемы с авторизацией, если каждый раз пересоздавать сокет.

Спасибо, буду гуглитть))
0
1 / 1 / 0
Регистрация: 10.04.2016
Сообщений: 7
15.03.2018, 11:31 6
Здравствуйте. Нужна помощь в реализации передачи файлов от клиентов серверу. Реализация на netty 4.1. Получилось реализовать чат, как его переделать для передачи файлов любого объема?

Сервер:
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
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;
/**
 *
 * @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();
        System.out.println("channelRead [" + talk.remoteAddress() + "] " + msg.toString());
        
        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 channelRead(ChannelHandlerContext ctx, int msg) throws Exception {
        Channel talk = ctx.channel();
        if ((int) msg != -1) {
            System.out.println("[" + talk.remoteAddress() + "] " + msg);
        }
    }
    
    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
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 javax.swing.JFileChooser;
 
/**
 *
 * @author nomid
 */
public class Client {
    public String HOST;
    public int PORT;
 
    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 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 + "\r\n");
                } else {
                    JFileChooser chooser = new JFileChooser();
                    int send = chooser.showDialog(null, "Send");
                    if (send == JFileChooser.APPROVE_OPTION) {
                        try {
                            File source = new File(chooser.getSelectedFile().getPath());
                            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;
                            while ((c = inputSR.read()) != -1) {
                                int integer = c;
                                System.out.print((char) integer);
                                System.out.print(": " + integer);
                                System.out.println("");
                                outSW.append((char) integer);
                                
//                                if (c != 10) {
//                                    channel.write(integer);
//                                } else {
                                    channel.writeAndFlush(integer);
                                    channel.flush();
//                                }
                            }
                            
                            inputSR.close();
                            outSW.close();
                            
                        } catch (Exception ex) {
                            System.out.println(ex.getMessage());
                        }
                        
                        channel.write(chooser.getSelectedFile().getPath());
                        channel.flush();
                    }
                }
            }
        } finally {
            group.shutdownGracefully();
        }
    }
    
    public static void main(String[] args) throws InterruptedException, IOException {
        new Client("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
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();
    }
}
Буду благодарен за любые идеи...
0
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
16.03.2018, 16:46
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
16.03.2018, 16:46
Помогаю со студенческими работами здесь

Сокеты и передача разных данных, разным клиентам
Добрый день уважаемые форумчане. У меня есть сервер:package org.poker.main; import...

Передача файлов через сокеты
Добрый вечер, Понимаю, что тема заезженная, но мне нужна помощь. Уже пол дня роюсь в интернете...

Сокет: Передача файлов/картинок через сокеты...
Знаю, что тема уже изжёвана, но у меня ничего не получается. Вопрос пока банальный, передача...

Передача файлов через сокеты в обоих направлениях
Нужно осуществить передачу файлов(от 2 и более за раз) через сокеты в обоих направлениях(клиент...

Передача файлов от сервера к клиенту через сокеты
как с поьощью сокетов передать файл от сервера к клиенту???

Передача файлов через сокеты для чата
Здравствуйте, проблема такая- чат на tclientsocket и tserversocket режим не блокирующий. Как...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
7
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru