Java客户端 - 服务器聊天(服务器不接收字符串)

时间:2012-03-14 16:25:06

标签: java

尝试制作一个简单的客户端服务器聊天程序。我已经去了,以便服务器读取用户输入,然后将其发送到客户端。然后客户端收到并显示它。然后让客户端读取用户输入并将其发送到服务器,但服务器不接收它。继承我的代码:

客户端:

import java.lang.*;
import java.io.*;
import java.net.*;
import java.util.Scanner;


class client {
   public static void main(String args[]) {
      try {
         Socket skt = new Socket("localhost", 1234);
         BufferedReader in = new BufferedReader(new
         InputStreamReader(skt.getInputStream()));
         System.out.print("Waiting for server to respond... \n");

         while (!in.ready()) {}
         System.out.print("Received Message: ");
         System.out.println(in.readLine()); // Read one line and output it

         System.out.print("\n");
         //in.close();

         System.out.print("Message:");
         Scanner sc = new Scanner (System.in);
         String data2 = sc.nextLine();
         PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
         System.out.print("Sending Message: '" + data2 + "'\n");
         out.print(data2);
         out.close();


      }
      catch(Exception e) {
         System.out.print("Whoops! It didn't work!\n");
      }
   }
}

服务器:

import java.lang.*;
import java.io.*;
import java.net.*;
import java.util.Scanner;



class server {


   public static void main(String args[]) {

      try {
         System.out.println("Waiting for client connection...");
         ServerSocket srvr = new ServerSocket(1234);
         Socket skt = srvr.accept();
         System.out.println("Client has connected!\n");
         System.out.print("Message:");
         Scanner sc = new Scanner (System.in);
         String data = sc.nextLine();
         PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
         System.out.print("Sending Message: '" + data + "'\n");
         out.print(data);

         BufferedReader in = new BufferedReader(new
         InputStreamReader(skt.getInputStream()));


         while (!in.ready()) {out.close();}      
         System.out.print("Received Message: ");
         System.out.println(in.readLine()); // Read one line and output it
         System.out.print("\n");


         //in.close();

         //in.close();
         //out.close();
         //skt.close();
         //srvr.close();
      }
      catch(Exception e) {
         System.out.print("Whoops! It didn't work!\n");
      }
   }
}

客户端和服务器都使用相同的代码进行发送/接收,因此我不明白服务器无法接收的原因。

干杯,

汤姆

1 个答案:

答案 0 :(得分:0)

print()发送文本但不发送新行。请尝试使用println()。

服务器上的readLine()等待你没有发送的新行。

顺便说一句:我不会测试in.ready()这可能比有用的恕我直言更令人困惑。