Форум программистов, компьютерный форум, киберфорум
Java: Сети
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.71/7: Рейтинг темы: голосов - 7, средняя оценка - 4.71
3 / 5 / 1
Регистрация: 03.10.2014
Сообщений: 91

Чат с отправкой файлов(Сокет)

19.12.2015, 17:24. Показов 1377. Ответов 2
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Помогите пожалуйста с отправкой файлов, чтобы можно было нажать кнопку и смог выбрать файл и его отправить
Вот application
Server
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
 
public class Server extends JFrame {
    private JTextField enterField;
    private JTextArea displayArea;
    private ObjectOutputStream output;
    private ObjectInputStream input;
    private ServerSocket server;
    private Socket connection;
    private int counter = 1;
 
    // set up GUI
    public Server()
    {
        super( "Server" );
 
        Container container = getContentPane();
 
        // create enterField and register listener
        enterField = new JTextField();
        enterField.setEditable( false );
        enterField.addActionListener(
                new ActionListener() {
 
                    // send message to client
                    public void actionPerformed( ActionEvent event )
                    {
                        sendData( event.getActionCommand() );
                        enterField.setText( "" );
                    }
                }
        );
 
        container.add( enterField, BorderLayout.NORTH );
 
        // create displayArea
        displayArea = new JTextArea();
        container.add( new JScrollPane( displayArea ),
                BorderLayout.CENTER );
 
        setSize( 300, 150 );
        setVisible( true );
 
 
        JButton button1 = new JButton("Button 1");//Кнопка для отправки файлов
        container.add(button1);
 
    } // end Server constructor
 
    // set up and run server
    public void runServer()
    {
        // set up server to receive connections; process connections
        try {
 
            // Step 1: Create a ServerSocket.
            server = new ServerSocket( 12345, 100 );
 
            while ( true ) {
 
                try {
                    waitForConnection(); // Step 2: Wait for a connection.
                    getStreams();        // Step 3: Get input & output streams.
                    processConnection(); // Step 4: Process connection.
                }
 
                // process EOFException when client closes connection
                catch ( EOFException eofException ) {
                    System.err.println( "Server terminated connection" );
                }
 
                finally {
                    closeConnection();   // Step 5: Close connection.
                    ++counter;
                }
 
            } // end while
 
        } // end try
 
        // process problems with I/O
        catch ( IOException ioException ) {
            ioException.printStackTrace();
        }
 
    } // end method runServer
 
    // wait for connection to arrive, then display connection info
    private void waitForConnection() throws IOException
    {
        displayMessage( "Waiting for connection\n" );
        connection = server.accept(); // allow server to accept connection
        displayMessage( "Connection " + counter + " received from: " +
                connection.getInetAddress().getHostName() );
    }
 
    // get streams to send and receive data
    private void getStreams() throws IOException
    {
        // set up output stream for objects
        output = new ObjectOutputStream( connection.getOutputStream() );
        output.flush(); // flush output buffer to send header information
 
        // set up input stream for objects
        input = new ObjectInputStream( connection.getInputStream() );
 
        displayMessage( "\nGot I/O streams\n" );
    }
 
    // process connection with client
    private void processConnection() throws IOException
    {
        // send connection successful message to client
        String message = "Connection successful";
        sendData( message );
 
        // enable enterField so server user can send messages
        setTextFieldEditable( true );
 
        do { // process messages sent from client
 
            // read message and display it
            try {
                message = ( String ) input.readObject();
                displayMessage( "\n" + message );
            }
 
            // catch problems reading from client
            catch ( ClassNotFoundException classNotFoundException ) {
                displayMessage( "\nUnknown object type received" );
            }
 
        } while ( !message.equals( "CLIENT>>> TERMINATE" ) );
 
    } // end method processConnection
 
    // close streams and socket
    private void closeConnection()
    {
        displayMessage( "\nTerminating connection\n" );
        setTextFieldEditable( false ); // disable enterField
 
        try {
            output.close();
            input.close();
            connection.close();
        }
        catch( IOException ioException ) {
            ioException.printStackTrace();
        }
    }
 
    // send message to client
    private void sendData( String message )
    {
        // send object to client
        try {
            output.writeObject( "SERVER>>> " + message );
            output.flush();
            displayMessage( "\nSERVER>>> " + message );
        }
 
        // process problems sending object
        catch ( IOException ioException ) {
            displayArea.append( "\nError writing object" );
        }
    }
 
    // utility method called from other threads to manipulate
    // displayArea in the event-dispatch thread
    private void displayMessage( final String messageToDisplay )
    {
        // display message from event-dispatch thread of execution
        SwingUtilities.invokeLater(
                new Runnable() {  // inner class to ensure GUI updates properly
 
                    public void run() // updates displayArea
                    {
                        displayArea.append( messageToDisplay );
                        displayArea.setCaretPosition(
                                displayArea.getText().length() );
                    }
 
                }  // end inner class
 
        ); // end call to SwingUtilities.invokeLater
    }
 
    // utility method called from other threads to manipulate
    // enterField in the event-dispatch thread
    private void setTextFieldEditable( final boolean editable )
    {
        // display message from event-dispatch  thread of execution
        SwingUtilities.invokeLater(
                new Runnable() {  // inner class to ensure GUI updates properly
 
                    public void run()  // sets enterField's editability
                    {
                        enterField.setEditable( editable );
                    }
 
                }  // end inner class
 
        ); // end call to SwingUtilities.invokeLater
    }
 
    public static void main( String args[] )
    {
        Server application = new Server();
        application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        application.runServer();
    }
 
}  // end class Server
Client
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
 
public class Client extends JFrame {
    private JTextField enterField;
    private JTextArea displayArea;
    private ObjectOutputStream output;
    private ObjectInputStream input;
    private String message = "";
    private String chatServer;
    private Socket client;
 
    // initialize chatServer and set up GUI
    public Client( String host )
    {
        super( "Client" );
 
        chatServer = host; // set server to which this client connects
 
        Container container = getContentPane();
 
        // create enterField and register listener
        enterField = new JTextField();
        enterField.setEditable( false );
        enterField.addActionListener(
                new ActionListener() {
 
                    // send message to server
                    public void actionPerformed( ActionEvent event )
                    {
                        sendData( event.getActionCommand() );
                        enterField.setText( "" );
                    }
                }
        );
 
        container.add( enterField, BorderLayout.NORTH );
 
        // create displayArea
        displayArea = new JTextArea();
        container.add( new JScrollPane( displayArea ),
                BorderLayout.CENTER );
 
        setSize( 300, 150 );
        setVisible( true );
 
    } // end Client constructor
 
    // connect to server and process messages from server
    private void runClient()
    {
        // connect to server, get streams, process connection
        try {
            connectToServer(); // Step 1: Create a Socket to make connection
            getStreams();      // Step 2: Get the input and output streams
            processConnection(); // Step 3: Process connection
        }
 
        // server closed connection
        catch ( EOFException eofException ) {
            System.err.println( "Client terminated connection" );
        }
 
        // process problems communicating with server
        catch ( IOException ioException ) {
            ioException.printStackTrace();
        }
 
        finally {
            closeConnection(); // Step 4: Close connection
        }
 
    } // end method runClient
 
    // connect to server
    private void connectToServer() throws IOException
    {
        displayMessage( "Attempting connection\n" );
 
        // create Socket to make connection to server
        client = new Socket( InetAddress.getByName( chatServer ), 12345 );
 
        // display connection information
        displayMessage( "Connected to: " +
                client.getInetAddress().getHostName() );
    }
 
    // get streams to send and receive data
    private void getStreams() throws IOException
    {
        // set up output stream for objects
        output = new ObjectOutputStream( client.getOutputStream() );
        output.flush(); // flush output buffer to send header information
 
        // set up input stream for objects
        input = new ObjectInputStream( client.getInputStream() );
 
        displayMessage( "\nGot I/O streams\n" );
    }
 
    // process connection with server
    private void processConnection() throws IOException
    {
        // enable enterField so client user can send messages
        setTextFieldEditable( true );
 
        do { // process messages sent from server
 
            // read message and display it
            try {
                message = ( String ) input.readObject();
                displayMessage( "\n" + message );
            }
 
            // catch problems reading from server
            catch ( ClassNotFoundException classNotFoundException ) {
                displayMessage( "\nUnknown object type received" );
            }
 
        } while ( !message.equals( "SERVER>>> TERMINATE" ) );
 
    } // end method processConnection
 
    // close streams and socket
    private void closeConnection()
    {
        displayMessage( "\nClosing connection" );
        setTextFieldEditable( false ); // disable enterField
 
        try {
            output.close();
            input.close();
            client.close();
        }
        catch( IOException ioException ) {
            ioException.printStackTrace();
        }
    }
 
    // send message to server
    private void sendData( String message )
    {
        // send object to server
        try {
            output.writeObject( "CLIENT>>> " + message );
            output.flush();
            displayMessage( "\nCLIENT>>> " + message );
        }
 
        // process problems sending object
        catch ( IOException ioException ) {
            displayArea.append( "\nError writing object" );
        }
    }
 
    // utility method called from other threads to manipulate
    // displayArea in the event-dispatch thread
    private void displayMessage( final String messageToDisplay )
    {
        // display message from GUI thread of execution
        SwingUtilities.invokeLater(
                new Runnable() {  // inner class to ensure GUI updates properly
 
                    public void run() // updates displayArea
                    {
                        displayArea.append( messageToDisplay );
                        displayArea.setCaretPosition(
                                displayArea.getText().length() );
                    }
 
                }  // end inner class
 
        ); // end call to SwingUtilities.invokeLater
    }
 
    // utility method called from other threads to manipulate
    // enterField in the event-dispatch thread
    private void setTextFieldEditable( final boolean editable )
    {
        // display message from GUI thread of execution
        SwingUtilities.invokeLater(
                new Runnable() {  // inner class to ensure GUI updates properly
 
                    public void run()  // sets enterField's editability
                    {
                        enterField.setEditable( editable );
                    }
 
                }  // end inner class
 
        ); // end call to SwingUtilities.invokeLater
    }
 
    public static void main( String args[] )
    {
        Client application;
 
        if ( args.length == 0 )
            application = new Client( "127.0.0.1" );
        else
            application = new Client( args[ 0 ] );
 
        application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        application.runClient();
    }
}
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
19.12.2015, 17:24
Ответы с готовыми решениями:

TCP-чат (не получается связать сокет через accept)
Никак не получается связать сокет через accept (программа дальше просто не идет). Не пойму почему:( Даже с кодом из учебника почему-то не...

Непонятки с отправкой файлов на почту
Вообщем нужно мне отправить файлы на почту, но они коем чудом не доходят "Сбой при отправке сообщения" Так вот как же я отправляю: ...

Пауза между отправкой файлов на ftp
Сделал себе скриптик, который закидывает файлы на фтп сервер. Только вот, файлы должны приходить на сервер в определенном порядке, чтобы...

2
90 / 89 / 23
Регистрация: 08.07.2014
Сообщений: 548
19.12.2015, 21:37
http://stackoverflow.com/quest... er-sockets
http://stackoverflow.com/quest... ng-sockets
0
1 / 1 / 3
Регистрация: 19.02.2015
Сообщений: 66
20.12.2015, 21:15
Там ты найдешь то что тебе надо.

github.com/Krowli/JavaUTP/tree/master/ClientServer_network
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
20.12.2015, 21:15
Помогаю со студенческими работами здесь

Нужны исходники локального чата с отправкой файлов
Ребят, помогите пожалуйста найти исходники чата с отправкой файлов и желательно, но не обязательно, с авторизацией.

Поиск файлов на всех дисках с последующей отправкой их на FTP
Всех приветствую. Прошу знатоков о помощи. У меня есть .bat файл, с помощью которого некоторые файлы (путь к которым указан в коде)...

Обратная форма без перезагрузки с отправкой нескольких файлов на почту
Здравствуйте Уважаемые программисты. Я сейчас с ума сойду. Столько перерыл... Я пытаюсь найти уже готовую форму для отправки писем на почту...

Почтовый клиент с отправкой файлов на почту. Ошибка: Undeclared identifier
Привет ребят. Помогите пожалуйста. Пишу почтовый клиент с отправкой файлов на почту. Но при компиляции выдаёт ошибку. ...

Обратная форма без перезагрузки с отправкой нескольких файлов на почту
Здравствуйте Уважаемые программисты. Я сейчас с ума сойду. Столько перерыл... Я пытаюсь найти уже готовую форму для отправки писем на почту...


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

Или воспользуйтесь поиском по форуму:
3
Ответ Создать тему
Новые блоги и статьи
Ритм жизни
kumehtar 27.02.2026
Иногда приходится жить в ритме, где дел становится всё больше, а вовлечения в происходящее — всё меньше. Плотный график не даёт вниманию закрепиться ни на одном событии. Утро начинается с быстрых,. . .
SDL3 для Web (WebAssembly): Сборка SDL3 из исходников с помощью CMake и Emscripten
8Observer8 27.02.2026
Недавно вышла версия 3. 4. 2 библиотеки SDL3. На странице официальной релиза доступны исходники, готовые DLL (для x86, x64, arm64), а также библиотеки для разработки под Android, MinGW и Visual Studio. . . .
SDL3 для Web (WebAssembly): Реализация движения на Box2D v3 - трение и коллизии с повёрнутыми стенами
8Observer8 20.02.2026
Содержание блога Box2D позволяет легко создать главного героя, который не проходит сквозь стены и перемещается с заданным трением о препятствия, которые можно располагать под углом, как верхнее. . .
Конвертировать закладки radiotray-ng в m3u-плейлист
damix 19.02.2026
Это можно сделать скриптом для PowerShell. Использование . \СonvertRadiotrayToM3U. ps1 <path_to_bookmarks. json> Рядом с файлом bookmarks. json появится файл bookmarks. m3u с результатом. # Check if. . .
Семь CDC на одном интерфейсе: 5 U[S]ARTов, 1 CAN и 1 SSI
Eddy_Em 18.02.2026
Постепенно допиливаю свою "многоинтерфейсную плату". Выглядит вот так: https:/ / www. cyberforum. ru/ blog_attachment. php?attachmentid=11617&stc=1&d=1771445347 Основана на STM32F303RBT6. На борту пять. . .
Камера Toupcam IUA500KMA
Eddy_Em 12.02.2026
Т. к. у всяких "хикроботов" слишком уж мелкий пиксель, для подсмотра в ESPriF они вообще плохо годятся: уже 14 величину можно рассмотреть еле-еле лишь на экспозициях под 3 секунды (а то и больше),. . .
И ясному Солнцу
zbw 12.02.2026
И ясному Солнцу, и светлой Луне. В мире покоя нет и люди не могут жить в тишине. А жить им немного лет.
«Знание-Сила»
zbw 12.02.2026
«Знание-Сила» «Время-Деньги» «Деньги -Пуля»
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru