我已經在Java中實現了一個簡單的聊天程序。然而,當我運行的代碼,並嘗試從客戶端發送郵件,我得到這個作爲輸出在服務器端客戶端無法在java聊天程序中向服務器發送消息
例如:
客戶:您好
服務器:ServerSocket的[地址= 0.0.0.0/0.0 .0.0,端口= 0,將localPort = 2000]
我得到任何消息我send..I我基本上是在本地主機上
工作這樣的來自客戶端的響應誰能幫助解決我的問題?
我的Java代碼:
class Client
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the key value");
int key=Integer.parseInt(br.readLine());
int random=(int)(Math.random()*50);
System.out.println(random);
int response=((int)random)%(key);
System.out.println(key);
System.out.println("response generated is "+response);
System.out.println("Authentication begins");
Socket echoSocket = new Socket("127.0.0.1", 2500);
BufferedReader sin=new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
PrintStream sout=new PrintStream(echoSocket.getOutputStream());
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = null;
String s;
DataOutputStream clientout=new DataOutputStream(echoSocket.getOutputStream());
clientout.writeInt(random);
clientout.writeInt(key);
clientout.writeInt(response);
System.out.println("client is"+response);
System.out.println("chat is started");
while (true)
{
System.out.print("Client : ");
s=stdin.readLine();
sout.println(s);
s=sin.readLine();
System.out.print("Server : "+s+"\n");
if (s.equalsIgnoreCase("BYE"))
break;
}
echoSocket.close();
sin.close();
sout.close();
stdin.close();
}
}
class Server
{
public static void main(String args[]) throws IOException
{
int random3=(int)(Math.random()*50);
int response2;
int response3;
int random2;
int key2;
ServerSocket s= new ServerSocket(2500);
Socket echoSocket=s.accept();
DataInputStream clientin=new DataInputStream(echoSocket.getInputStream());
BufferedReader cin=new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
PrintStream cout=new PrintStream(echoSocket.getOutputStream());
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
String s1;
random2=clientin.readInt();
key2=clientin.readInt();
response2=clientin.readInt();
System.out.println(key2);
response3=(random2)%(key2);
System.out.println("server is"+response2);
if(response2==response3)
{
System.out.println("client is authenticated..chat starts");
while (true)
{
s1=cin.readLine();
if (s1.equalsIgnoreCase("END"))
{
cout.println("BYE");
break;
}
System. out.print("Client : "+s+"\n");
System.out.print("Server : ");
s1=stdin.readLine();
cout.println(s1);
}
}
s.close();
echoSocket.close();
cin.close();
cout.close();
stdin.close();
}
}
請發佈相關代碼,以便我們可以開始幫助你解決問題。 – momo
momo:我發佈代碼 –
Parth_90,我在下面給出了答案。我認爲你基本上只是把變量混合起來 – momo