我正試圖做一個來回發送消息的程序。我似乎已經做到了;但是,爲了讓消息來回發送,客戶端必須首先發送消息以便對話啓動。聊天服務器客戶端來回郵件
我想知道如何根據誰想要先發送消息發送消息。此外,他們似乎處於交替式的對話中,如果服務器或客戶端發送兩條直接消息,它將會出現錯誤...我真的希望這是有道理的。
SERVER:
import java.io.*;
import java.net.*;
class Server
public static void main(String arg[]) throws IOException {
ServerSocket ss = null;
try{
ss = new ServerSocket(1111);
}catch(IOException e){
System.out.println("Failed");}
Socket sock = null;
try{
sock = ss.accept();
}catch(IOException io){
System.out.println("Socket Failed");}
System.out.println("Connection Successful..");
BufferedReader input = new BufferedReader(new InputStreamReader(sock.getInputStream()));
PrintStream output = new PrintStream(sock.getOutputStream());
BufferedReader ServerMessage = new BufferedReader(new InputStreamReader(System.in));
String Message;
while(true){
message= input.readLine();
System.out.println("Clien: " + message);
System.out.println("Server: ");
message = ServerMessage.readLine();
output.println(message);
System.out.println("Server: " + message);
}
}
}
客戶:
import java.io.*;
import java.net.*;
class Server
public static void main(String arg[]) throws IOException {
Socket sock = null;
try{
sock = new Socket("127.0.0.1", 1111);
}catch(IOException io){
System.out.println("Socket Failed");}
System.out.println("Connection Successful..");
BufferedReader in = new BufferedReader(new `InputStreamReader(sock.getInputStream()));`
PrintStream out = new PrintStream(sock.getOutputStream());
BufferedReader ClientMessage = new BufferedReader(new InputStreamReader(System.in));
String Message;
while(true){
System.out.print("Client: ");
Message = ClientMessage.readLine();
output.println(Message);
System.out.println("Client: " + Message);
Message = in.readLine();
System.out.println("Server: " + Message);
}
}
}
這裏是我創建的一個框架,用於創建'ServerSocket's來照顧一些涉及的管道:http://sourceforge.net/p /土族/代碼/ HEAD /樹/ tjacobs/IO/ServerSocketEx。 java的。希望這對你有所幫助 – ControlAltDel