Привет, я хочу запрограммировать простой код: сервер и сокет
Сервер - запускает сокет - хочет подключить серверы - принимает его
сервер - ждет команды от сокета сокета -пишет команду на потоковый сервер - хочет ответить на потоке
ajsiodjasodasodsa не работает?!
это сокет, который подключается к серверу
try (Socket socket = new Socket("localhost", 1234);) {
// get the outputstream to write a command to the server as soon as it is
// connected:
OutputStream outputStream = socket.getOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
// this is the command
bufferedWriter.write("LISTPARTS");
bufferedWriter.flush();
// Now it should open a input stream to read the resonse of the server!
InputStream inputStream = socket.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
System.out.println("\nafter creating the reader");
String readLine;
while ((readLine = bufferedReader.readLine()) == null) {
System.out.println("what:" + readLine);
}
Это сервер:
while (true) {
try (ServerSocket server = new ServerSocket(1234);) {
System.out.println("wait for Client");
Socket socket = server.accept(); // wartet bis akzeptiert
System.out.println("Client was accepted");
// Open input stream because server waits for a command:
InputStream inputStream = socket.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
// wait for command
System.out.println("wait for command");
String readLine;
while ((readLine = bufferedReader.readLine()) == null) {
System.out.println("wait for client");
}
System.out.println("read line:" + readLine);
// here it should look if the command works ( this works fine )
if (readLine.equals("LISTPARTS")) {
System.out.println("Commando: listparts");
// for responding the server opens a writer to write the response!
OutputStream outputStream = socket.getOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
// this method write onto the stream ( it should work normaly !)
circuit.dumpParts(bufferedWriter);
bufferedWriter.flush();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
это результат основного выхода серверов на консоли:
Server- Main
wait for Client
Client was accepted
wait for command
ирозетки консольные:
after creating the reader