简体   繁体   English

服务器未通过套接字通信接收

[英]Server not receiving in socket communication

I'm trying to make a Java program in which the server generates a random number and, after establishing a connection with a client, lets it guess the number. 我正在尝试制作一个Java程序,在该程序中服务器生成一个随机数,并在与客户端建立连接后让其猜测该数。 However, they both don't seem able to receive each others' messages. 但是,他们似乎都无法接收彼此的消息。
Server side: 服务器端:

package numberguessserv;

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

public class NumberGuessServ {

    public static void main(String[] args) {
        Scanner inpkb = new Scanner(System.in);
        Random randomGenerator = new Random();
        int randomNum = randomGenerator.nextInt(10);
        String number = Integer.toString(randomNum);
        int port;
        boolean isGuessed = false;
        String msgReceived;
        Socket connect = new Socket();
        System.out.print("port: ");
        port = inpkb.nextInt();
        try {
            ServerSocket clSock = new ServerSocket(port);
            System.out.println("Waiting...");
            connect = clSock.accept();
            System.out.println("Connection established with"+connect.getInetAddress());
            InputStreamReader isr = new InputStreamReader(connect.getInputStream());
            BufferedReader isrBuff = new BufferedReader(isr);
            OutputStreamWriter osw = new OutputStreamWriter(connect.getOutputStream());
            BufferedWriter oswBuff = new BufferedWriter(osw);
            while (!isGuessed) {
                msgReceived = isrBuff.readLine();
                System.out.println("Number received: "+msgReceived);
                if (msgReceived.equals(number)) {
                    isGuessed = true;
                    oswBuff.write("Right!");
                    oswBuff.flush();
                }
                else {
                    oswBuff.write("Wrong!");
                    oswBuff.flush();
                }
                if (isGuessed)
                    System.out.println("Number was guessed right.");
                else
                    System.out.println("Number was guessed wrong.");
                }
            }
            catch (Exception ex) {
                System.out.println("An exception has occurred: "+ex);
            }
            finally {
                try {
                    connect.close();
                }
                catch (Exception ex) {
                    System.out.println("An exception has occurred: "+ex);
                }
           }
      }
 }

Client side: 客户端:

package numberguessclient;

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

public class NumberGuessClient {

    public static void main(String[] args) {
        Scanner inpkb = new Scanner(System.in);
        int port;
        String IP;
        boolean isGuessed = false;
        String number, msg;
        Socket serv = new Socket();
        System.out.print("IP: ");
        IP = inpkb.next();
        System.out.print("port: ");
        port = inpkb.nextInt();
        try {
            serv = new Socket(IP,port);
            System.out.println("Connetion established with"+serv.getInetAddress());
            InputStreamReader isr = new InputStreamReader(serv.getInputStream());
            BufferedReader isrBuff = new BufferedReader(isr);
            OutputStreamWriter osw = new OutputStreamWriter(serv.getOutputStream());
            BufferedWriter oswBuff = new BufferedWriter(osw);
            while (!isGuessed) {
                System.out.print("number: ");
                number = inpkb.next();
                oswBuff.write(number);
                oswBuff.flush();
                System.out.println("Number sent.");
                msg = isrBuff.readLine();
                System.out.println("The reply was received: "+msg);
                if (msg.equals("Right!")) {
                    isGuessed = true;
                    System.out.println(msg);
                }
                else {
                    System.out.println(msg+"\nTry again...");
                }
            }
        }
        catch (Exception ex) {
            System.out.print("An exception has occurred: "+ex);
        }
        finally {
            try {
                serv.close();
            }
            catch (Exception ex) {
                System.out.print("An exception has occurred: "+ex);
            }
        }
    }
}

That's expected. 那是意料之中的。 Both ends read using 两端使用

isrBuff.readLine();

So, they both expect the other end to send a line. 因此,他们都希望另一端发送一条线路。 But none of them sends a line. 但是他们都没有发送电话。 They both do 他们俩都做

oswBuff.write(number);
oswBuff.flush();

That sends some characters, but doesn send any newline character. 这会发送一些字符,但不会发送任何换行符。 The receiving end doesn't have any way to know that the end of line has been reached, and it thus continues blocking until it receives the EOL. 接收端无法知道已到达行尾,因此它将继续阻塞直到接收到EOL。

The readLine () waits for the end of line. readLine ()等待行尾。 Unless and until it gets a new line character, it will wait up there reading. 除非并且直到得到新的换行符,否则它将在那里等待读取。

So, you need to give a new line characer '\\n' every time you give an input to the output stream so that the readLine() reads a new line character and does not wait. 因此,每次向输出流提供输入时,都需要给换行符'\\ n',以便readLine()读取换行符并且不等待。

Currently in your code, you need to give a new line character everytime you are giving input by doing the following: 当前在您的代码中,每次执行以下操作时,您都需要给换行符:

oswBuff.write("any message");
oswBuff.write('\n');      //add this statement everywhere you are writing to the output stream
oswBuff.flush();

This complies well for both the server as well as client. 这对服务器和客户端都非常适用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM