我正在嘗試進行簡單的聊天。我有一個處理更多客戶端的服務器。這是我到現在爲止所做的:連接,我可以在我的服務器上識別哪個客戶端正在發送消息,但問題是客戶端上無法像服務器上那樣獲得完整對話。例如,使用套接字連接的簡單聊天
Client_1 (writing)
msg : hi
Client_2 (writing)
msg : hi from cl2
results
Server :
Client_1 : hi
Client_2 : hi from cl2
Client_1
Client_1 : hi
Client_2
Client_2 :hi from cl2
我想實現這兩個客戶端具有相同的服務器信息。
My Server Script :
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(1900);
System.out.println("waiting");
while (true) {
Socket sock = server.accept();
System.out.println("Client nou conectat !");
ClientHandler cH = new ClientHandler(sock);
cH.start();
}
}
}
class ClientHandler extends Thread {
BufferedReader in;
PrintWriter out;
ClientHandler(Socket sock) throws IOException {
out = new PrintWriter(new OutputStreamWriter(sock.getOutputStream()),
true);
in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
}
public void run() {
try {
out.println("Hello from server"); //hello message to client
while (true) {
String linie = in.readLine();
if (linie==null)
return;
System.out.println(linie); //message from client
out.println(linie);
}
}catch(Exception e) {e.printStackTrace();}
}
}
客戶端腳本
public class Client {
public static void main(String[] args) throws Exception {
// String ip ="192.168.1.12";
String ip ="localhost";
Socket sock = new Socket(ip, 1900); // localhost daca ii pe
// acelasi pc serverul
// si clientul,altfel
// IPul
PrintWriter out = new PrintWriter(new OutputStreamWriter(
sock.getOutputStream()), true);
BufferedReader in = new BufferedReader(new InputStreamReader(
sock.getInputStream()));
String linie = in.readLine();
System.out.println("Server :" + linie);//meesage from server
BufferedReader console = new BufferedReader(new InputStreamReader(
System.in));
while (true) {
linie = console.readLine();
out.println("Client_1 :"+linie); // sending to server
String linie2 =in.readLine();
System.out.println(linie2); //resend message to client
}
}
}
我希望我很好地解釋我的問題:d。謝謝大家的建議
你沒有告訴你從哪裏複製粘貼它? – Makky
那麼,我有一個功課,以確定每個客戶端何時發送消息,並獲得相同的輸出在客戶端作爲服務器端 – Petrica
我需要一些提示,如何從客戶端獲取信息到另一個... – Petrica