我來自波蘭,所以我對任何錯誤感到抱歉。
我編寫了一段時間的小型服務器和客戶端連接,當我停下來討厭的問題。當我從客戶端發送服務器信息(字符串)時,服務器可以得到它,但不能響應它。Java無法獲得客戶端或服務器響應
這裏是代碼。
客戶
private static Socket socket;
public static void main(String args[]){
try{
String host = "localhost";
int port = 25002;
InetAddress address = InetAddress.getByName(host);
socket = new Socket();
socket.connect(new InetSocketAddress(host, port), 5000);
//Send the message to the server
System.out.println("< "+sendMessage(socket));
//socket.shutdownOutput();
System.out.println("> "+getMessage(socket));
}catch (SocketTimeoutException e){
System.out.println(e.getMessage()); // changed
}catch (IOException e){
System.out.println(e.getMessage()); // changed
}catch (IllegalBlockingModeException e){
System.out.println(e.getMessage()); // changed
}catch(IllegalArgumentException e){
System.out.println(e.getMessage()); // changed
}finally{
//Closing the socket
try{
socket.close();
}catch(Exception e){
System.out.println(e.getMessage()); // changed
}
}
}
public static String sendMessage(Socket client){
try {
String message = "test";
PrintWriter writer = new PrintWriter(client.getOutputStream(), true);
writer = new PrintWriter(client.getOutputStream(), true);
writer.print(message);
writer.flush();
writer.close();
return message;
} catch (IOException e) {
System.out.println(e.getMessage()); // changed
return "false";
}
}
public static String getMessage(Socket client){
try {
BufferedReader socketReader = new BufferedReader(new InputStreamReader(client.getInputStream()));
return socketReader.readLine();
} catch (IOException e){
System.out.println(e.getMessage()); // changed
return "false";
}
}
和..服務器
public class kRcon{
private static Socket socket;
private static ServerSocket serverSocket;
private static Thread u;
private static class Server extends Thread {
public void run() {
int port = 25002;
try {
serverSocket = new ServerSocket(port);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while(true) {
try {
socket = serverSocket.accept();
BufferedReader socketReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter socketWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
String str = socketReader.readLine();
socketReader.close();
System.out.println(str);
socketWriter.write("test");
socketWriter.flush();
socketWriter.close();
}
}catch (IOException e1) {
e1.printStackTrace();
}
}
public static void init(){
try {
u = new Server();
u.setName("Server");
u.start();
} catch (IOException e) {
System.out.println(e.getMessage()); // changed
}
}
}
結果
如果我啓動服務器首先看起來不錯。 所以,我開始parametr「測試」客戶端,NAD輸出到控制檯是:
< test
Socket is closed // changed
在服務器端中的控制檯I具有:
"test"
Socket is closed // changed
我試圖關機輸入和輸出以及不能工作..我現在不知道該做什麼。請幫助:C
編輯2015年4月3日
我已經改變了與評論「改變」行。
對於Google和讀者 要解決問題,請不要在客戶端關閉StreamReaders和StreamWriters。 感謝EJP,尋求幫助!
來自波蘭的問候。
美麗!有用! Thaaaank你! – kGielo 2015-04-03 08:37:10