간단한 서버 클라이언트 프로그램을 작성하려고하는데 문제가 있습니다. 클라이언트에서 서버로 데이터를 보낼 수는 있지만 서버에서 데이터를 보낼 수 없습니다 (예 :) 클라이언트에서 받아 봐 :(
그래서 서버에서 데이터를 전송하고 클라이언트에서 받아 봐하는 방법을Java 소켓 질문
서버 :?
//this is in a thread
try {
server = new ServerSocket(1365);
} catch (IOException e) {
e.printStackTrace();
}
while (!exit) {
try {
clientSocket = server.accept();
is = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());
while ((line = is.readLine()) != null) {
System.out.println("Message from client: " + line);
//if (line.equals("exit")) {
// exit = true;
//}
if (line.equals("say something")) {
os.write("something".getBytes());
}
}
} catch (IOException e) {
e.printStackTrace();
}
try {
is.close();
} catch (IOException ex) {
ex.printStackTrace();
}
os.close();
}
클라이언트 :
try {
socket = new Socket(host, 1365);
os = new DataOutputStream(socket.getOutputStream());
is = new DataInputStream(socket.getInputStream());
} catch (UnknownHostException e) {}
if (socket != null && os != null && is != null) {
try {
os.writeBytes("say something");
//get the answer from server
os.close();
is.close();
socket.close();
} catch (IOException e) {}
}
(긴 코드는 죄송합니다.)
미리 감사드립니다.
왜 버퍼링 된 문자 스트림 대신 DataInputStream 및 DataOutputStream을 사용해야하는 특별한 이유가 있습니까? – Vasil
"say something"을 받았을 때 서버가 응답하는 것처럼 보입니다. 왜 그것이 전혀 응답하지 않을 수 있습니다. 또한 서버의 출력 스트림이 PrintStream 인 이유는 무엇입니까? –
@ MasterPeter : 클라이언트는 "say something"을 보내도록 하드 코딩되어 있으므로 Jani가 소켓을 테스트하는 데 사용하는 코드를 버리는 것입니다. –