簡體   English   中英

在JAVA中建立客戶端服務器通信?

[英]Establishing a client server Communication in JAVA?

我想在客戶端和服務器之間執行雙向通信,到目前為止,我已經實現了雙向通信。 我在JAVA中的代碼如下所示:

服務器端

    public class server{
        @SuppressWarnings("deprecation")
        public static void main(String[] args)
        {
            try{
            ServerSocket s=new ServerSocket(9998);
            Socket ss=s.accept();
            DataInputStream din=new DataInputStream(ss.getInputStream());
            DataInputStream uip=new DataInputStream(System.in);
            DataOutputStream dout=new DataOutputStream(ss.getOutputStream());
            System.out.println("Enter message to send to client\n");
            String stc=uip.readLine();
            dout.writeBytes(""+stc);
            din.close();
            dout.close();
            uip.close();    
        }
            catch(Exception e)
            {
                System.out.println(e);
            }`enter code here`
    }
    }

客戶端

   public class client{
    public static void main(String[] args)
    {
        try{
        Socket ss=new Socket("localhost",9998);
        DataInputStream din=new DataInputStream(ss.getInputStream());
        DataInputStream uip=new DataInputStream(System.in);
        DataOutputStream dout=new DataOutputStream(ss.getOutputStream());
        String msg=din.readLine();
        System.out.println("Received msg is "+msg);

        din.close();
        dout.close();
        uip.close();


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

我試圖在客戶端獲取輸入,並嘗試以相同的方式發送到服務器。 但這沒用。 我在哪里弄錯了? 我應該如何實現雙向溝通。

在客戶端,我從用戶那里得到輸入,並使用.writeBytes(value); 並在服務器端的din中執行了readLine() ,就像我上面以一種方式進行的通信一樣。 但這是行不通的。 我在哪里做錯了?

我假設您正在不同的進程中運行兩個程序,並且只期望從服務器發送的客戶端上有結果。 從客戶端,您沒有向服務器發送任何內容。

如果沒有出現任何錯誤,請嘗試刷新流,例如:

dout.writeBytes(""+stc);
dout.flush();

來自注釋:添加了以下代碼。

在服務器端接收代碼

// this is your code on server
dout.writeBytes(""+stc);
//Add this code 
String msgServer = din.readLine();
System.out.println("Received msg on Server: " + msgServer );

添加客戶端代碼:

// this is your code on client
System.out.println("Received msg is "+msg);
dout.writeBytes("Test data from client");
dout.flush();

創建雙重通信系統的最佳方法是創建兩個線程(一個用於寫消息,另一個用於接收消息)(在客戶端和服務器端)。

偵聽線程會自己接收一條消息,然后執行某些操作。 如果需要響應,則創建響應並將其添加到隊列中。

編寫線程定期檢查要發送的消息隊列。 如果有,則將其發送。

這是雙向客戶端服務器通信的最佳方法。“ dout.shutdownOutput();” 在客戶端的send函數之后編寫此行代碼。此函數名為半套接字關閉,將有助於來回通信。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM