簡體   English   中英

Java客戶端-服務器聊天(服務器未接收到字符串)

[英]Java client-server chat (server not receiving string)

嘗試制作一個簡單的客戶端服務器聊天程序。 我已經去過了,以便服務器讀取用戶輸入,然后將其發送到客戶端。 客戶端然后接收並顯示它。 然后,我讓客戶端讀取用戶輸入並將其發送到服務器,但是服務器未收到它。 這是我的代碼:

客戶:

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");
      }
   }
}

客戶端和服務器都使用相同的代碼進行發送/接收,所以我不明白為什么服務器無法接收。

干杯,

湯姆

print()發送文本,但不發送新行。 請嘗試使用println()。

服務器上的readLine()等待不發送的新行。

順便說一句:我不會測試in.ready()這比有用的恕我直言更容易造成混淆。

暫無
暫無

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

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