라이브 메신저 응용 프로그램을 만들려고합니다. 그러나 이유없이 ObjectInputStream에서 readObject를 시도 할 때 코드가 중단됩니다. 예외는 발생하지 않습니다.readObject가 응용 프로그램을 중단합니다.
try {
System.out.println("Trying to connect to server");
socket = new Socket(InetAddress.getByName("localhost"),6789);
System.out.println("Connected to server");
inputStream = new ObjectInputStream(socket.getInputStream());
outputStream = new ObjectOutputStream(socket.getOutputStream());
outputStream.flush();
System.out.println("Streams are set up.");
window.toggleTyping(true);
System.out.println("Typing is now enabled");
String inputMsg = null;
do {
try {
System.out.println("Reading object");
inputMsg = (String)inputStream.readObject();
System.out.println("Object read");
} catch(ClassNotFoundException ee) {
System.out.println("Clas not found exception");
ee.printStackTrace();
}
} while(!inputMsg.equalsIgnoreCase("/exit"));
closeConnection();
}catch(IOException ex) {
ex.printStackTrace();
}
마지막으로 출력되는 메시지는 "개체 읽기"입니다.
try {
serverSocket = new ServerSocket(6789);
System.out.println("Socket created. About to accept connections");
Socket s = serverSocket.accept();
new Thread(new Chat(s)).start();
} catch(IOException e) {
e.printStackTrace();
}
그리고 클래스 채팅 :
public class Chat implements Runnable {
private Socket socket;
private ObjectOutputStream outputStream;
private ObjectInputStream inputStream;
public Chat(Socket s) {
System.out.println("Chat class constructor called");
this.socket = s;
try {
outputStream = new ObjectOutputStream(socket.getOutputStream());
outputStream.flush();
inputStream = new ObjectInputStream(socket.getInputStream());
System.out.println("Chat streams are now set up");
}catch(IOException ex) {
ex.printStackTrace();
}
}
private void closeChat() {
try {
outputStream.close();
inputStream.close();
socket.close();
System.out.println("Chat is now closed");
}catch(IOException ex) {
ex.printStackTrace();
}
}
@Override
public void run() {
System.out.println("Chat class method run called");
try {
outputStream.writeObject("Connection is cool");
outputStream.flush();
System.out.println("Text sent");
String inputMsg = "";
do {
try {
inputMsg = (String)inputStream.readObject();
System.out.println("Message read:"+inputMsg);
}catch(ClassNotFoundException e) {
e.printStackTrace();
}
}
while(!inputMsg.equalsIgnoreCase("/exit"));
closeChat();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
이유 모든 대화에서 다른 스레드가 내가 언젠가 한 채팅에서 여러 일을 구현할 계획입니다 것입니다.
의 readObject를 (생성 한 후)이되는 OutputStream의 immediatley를 플러시 할 필요가 없습니다 차단 호출입니다. 아무 것도 없으면 객체를 읽을 때까지 기다립니다. 더 나은 시간 초과 및 확인 사용 – Shriram
서버가 개체를 보내고 플러시합니까? 서버 코드는 어디에 있습니까? –
@Shriram 어떻게 확인할 수 있습니까? – Bebras