2013-12-12 156 views
3

我試圖創建一個簡單的客戶端/服務器套接字通信應用程序(聊天客戶端)。我花了無數個小時來看看如何解決這個問題,但仍然沒有運氣,我可以將消息發送到服務器,但我堅持將消息從服​​務器發送回客戶端。Java服務器套接字響應

我相信問題是我發送回來之後如何從服務器獲取消息,我刪除了我所擁有的是我無法工作的InputStreamReader。

Server.java

public class Server extends Thread { 
@SuppressWarnings("unused") 
private static Socket socket; 
static int port = 1337; 
static ObjectOutputStream output; 

@SuppressWarnings("resource") 
public static void main(String[] args) throws IOException{ 
    ServerSocket ss = new ServerSocket(port); 
    System.out.println("Server started on port: " + port); 
    while(!Thread.interrupted()){ 
     try { 
      Socket clientSocket = ss.accept(); 
      DataInputStream dis = new DataInputStream(clientSocket.getInputStream()); 
      PrintStream output = new PrintStream(clientSocket.getOutputStream()); 
      String str = (String)dis.readUTF(); 
      String[] split = str.split("-"); 
      String subStringUsername = split[0]; 
      String subStringMessage = split[1]; 
      Date date = new Date(); 
      SimpleDateFormat sdf = new SimpleDateFormat("h:mm:ss a"); 
      String formattedTimestamp = sdf.format(date); 
      System.out.println("Message from " + subStringUsername + ": " + subStringMessage + " - at " + formattedTimestamp); 
      output.flush(); 

      output.println("Message received! Hello client!"); 
      System.out.println("Reply sent"); 
      output.flush(); 

      //TODO create new thread handle new users instead of Thread sleep 
      //TODO chat commands and user ID/can't be existing user 

      Thread.sleep(500); 
     } 
     catch(Exception e){ 
      System.out.println(e); 
     } 
    } 
} 

getMessage.java

public class GetMessage extends Thread {  
    public void run(){ 
     while(true) { 
      InputStreamReader be = new InputStreamReader(); 
     } 
    } 
} 

(我提前馬虎代碼道歉)這是我已經離開我刪除了所有的getMessage類在挫折中,我將getMessage作爲一個線程運行,我不知道這是最好的方法。我已經嘗試了10種方法從服務器獲取消息,但仍然沒有運氣,如果有人能指出我朝着正確的方向,我會非常感激。

+2

不要爲馬虎代碼道歉結束。改進它,然後發佈它。 – rzymek

+2

你爲什麼使用'DataInputStream'?客戶端是否也是一個使用'DataOuputStream'發送數據的Java程序?如果不是,那麼這可能不起作用,因爲'DataInputStream'旨在以編碼形式發送Java原始值,而不是通用數據。 –

回答

5

的readUTF塊,直到它接收輸入的結束,只能讀通過所傳遞的數據writeUTF方法。

參考:進行更完整的討論。

readUTF() causing Android app to hang

Also check out the docs

,你可能會想更換

DataInputStream dis = new DataInputStream(clientSocket.getInputStream()); 

BufferedReader reader = new BufferedReader(
     new InputStreamReader(clientSocket.getInputStream())); 

dis.readUTF(); 

String str = reader.readLine(); 

,或者,如果你不使用新的生產線將郵件標記爲

char[] buffer = new char[1024]; 
int read = 0; 
StringBuilder sb = new StringBuilder(); 

while ((read = reader.read(buffer, 0, buffer.length)) > 0) { 
    sb.append(buffer, 0, read); 
    // conduct some test that when passes marks the end of message, then break; 
} 
reader.close(); 

String str = sb.toString().trim(); 
+1

請勿發佈猜測。這只是混淆了這個問題,如果你錯了。 –

+1

'sb.append(buffer,0,read)'就足夠了。您不需要創建第三個副本。 – EJP

+0

感謝您的提示。 – robbmj

1

請將flush.close()放在flush方法之後,或者一旦完成刷新out流。

此外,我會用這樣的事情來實現一個聊天應用程序。它還使用Java Swings繪製客戶端和服務器窗口。用它作爲參考。這裏的格式可能沒什麼馬虎。

這是我的客戶端代碼:

public class Client 
{ 
private Socket s; 
private Scanner input; 
private PrintWriter output; 
private ChatFrame frame; 
static String s1; 

public Client(int port) throws IOException 
{ 
    s = new Socket("127.0.0.1", port); 
    input = new Scanner(s.getInputStream()); 
    output = new PrintWriter(s.getOutputStream()); 

} 
public static void main(String[] args) throws java.io.IOException 
{ 
    System.out.println("Enter The port No. :"); 
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
    String s = br.readLine(); 
    System.out.println("Enter Name : "); 
    br = new BufferedReader(new InputStreamReader(System.in)); 
    s1 = br.readLine(); 
    final Client client = new Client(Integer.parseInt(s)); 
    EventQueue.invokeLater(new Runnable() 
     { 
      public void run() { 
      client.frame = new ChatFrame(client.output,s1); 

      } 
     }); 

    String ClientChat = ""; 
    while(true) 
    { 
     if(client.input.hasNextLine()) 
     { 
      ClientChat = client.input.nextLine(); 
      client.frame.Chat(ClientChat);         
     } 
    } 
    } 
} 
class ChatFrame 
{ 
    JFrame jf; 
    JPanel jp; 
    JTextArea jta1,jta2; 
    JButton jb; 
    public ChatFrame(final PrintWriter output, final String Name) 
     { 
      jf = new JFrame(); 
      jf.setTitle(Name); 
      jf.setSize(800,600); 
      jp = new JPanel(); 
      jp.setBounds(0,0,800,600); 
      jta1 = new JTextArea(); 
      jta2 = new JTextArea(); 
      jta1.setBounds(20,10,760,390); 
       jta1.setBorder(BorderFactory.createLineBorder(Color.BLACK,2)); 
      jta2.setBounds(20,420,550,100); 
      jta2.setBorder(BorderFactory.createLineBorder(Color.BLACK,2)); 
      jb = new JButton("SEND"); 
      jb.setBounds(590,420,190,100); 
      jp.add(jb); 
      jp.add(jta1); 
      jp.add(jta2); 
      jp.setLayout(null); 


    ActionListener Action = new ActionListener() { 
    public void actionPerformed(ActionEvent e) { 
      String str = Name + " : " + jta2.getText(); 
      if(str.length() > 0) 
       { 
        output.println(str); 
        output.flush(); 
        jta2.setText(""); 
        jta2.grabFocus(); 
       } 
     } 
    }; 
    jb.addActionListener(Action); 
    jf.add(jp); 
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    jf.setVisible(true); 
    } 
    public void Chat(String MSG) 
    { 
      jta1.append(MSG + "\n"); 
      StringTokenizer st = new StringTokenizer(MSG,":"); 
      int flag = 0; 
      if(st.hasMoreElements()) 
       { 
        if(st.nextElement() == "bye" && flag == 0) 
         { 
          jf.setVisible(false); 
          jf.validate(); 
          System.exit(0); 
         } 
        flag = 1; 
       } 
     } 
} 

,這裏是我的服務器代碼:

public class MyServer 
{ 
    Hashtable<Socket,PrintWriter> output = new Hashtable<Socket,PrintWriter>(); 
    ServerSocket ss; 
    Socket s; 
    public void MakeConn() 
     { 
      try 
       { 
        ss = new ServerSocket(1001); 
        while(true) 
        { 
         s = ss.accept(); 
         System.out.println("Connection from " + s); 
         PrintWriter outMsg = new PrintWriter(s.getOutputStream()); 
         output.put(s,outMsg); 
         new ServerThread(this,s); 
        } 
       } 
      catch(Exception E) 
       { 

       } 
     } 

    public void tellEveryOne(String msg) 
    { 
     synchronized(output) 
     { 
      Enumeration keys = output.keys(); 
      while (keys.hasMoreElements()) 
       { 
        Socket ss = (Socket)keys.nextElement(); 
        PrintWriter outMsg = output.get(ss); 
        outMsg.println(msg); 
        outMsg.flush(); 
       } 
     } 
    } 
    public void ConnectionClose(Socket socket) 
    { 
     try 
      { 
       output.remove(socket); 
       socket.close(); 
      } 
     catch(IOException e) 
      { 

      } 
    } 
public static void main(String[] args) 
{ 
    MyServer ms = new MyServer(); 
    ms.MakeConn(); 
} 
} 

class ServerThread extends Thread 
    { 
     MyServer server; 
     Socket socket; 

     public ServerThread(MyServer server, Socket socket) 
      { 
       this.server = server; 
       this.socket = socket; 
       this.start(); 
      } 
     public void run() 
      { 
       try 
        { 
         Scanner input = new Scanner(socket.getInputStream()); 
         String inMsg; 
         String ByeMsg; 
         while(true) 
          { 
            if(input.hasNextLine()) 
            { 
              inMsg = input.nextLine(); 
             System.out.println(inMsg); 
             StringTokenizer st = new StringTokenizer(inMsg,":"); 
             int flag = 0; 
             if(st.hasMoreElements()) 
              { 
               if(st.nextElement() == "bye" && flag == 0) 
                { 
                 input.close(); 
                 socket.close(); 
                 break; 
                } 
               flag = 1; 
              } 
              server.tellEveryOne(inMsg); 
            } 
          } 
        } 
       catch(IOException E) 
        { 
        } 
       finally 
        { 
         server.ConnectionClose(socket); 
        } 
      } 

    }