简体   繁体   English

服务器、客户端套接字实现

[英]Server, Client socket implementation

Am writing a Server, client chat program using Java Socket.正在使用 Java Socket 编写服务器、客户端聊天程序。 Here is my code for the Server socket class.这是我的服务器套接字类代码。

import java.io.*;
import java.net.*;

public class Main {

    public static void main(String[] args) throws IOException {

        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(8085);
        } catch (IOException ex) {
            System.out.println("IO Error, " + ex);
            System.exit(1);
        }
        Socket clientSocket = null;
        System.out.println("Listening for incoming connections");
        try {
            clientSocket = serverSocket.accept();
        } catch (IOException ex) {
            System.out.println("Failed to accept connection " + ex);
            System.exit(1);
        }
        System.out.println("Connection Successful");
        System.out.println("Listening to get input");
        PrintStream output = new PrintStream(clientSocket.getOutputStream(), true);
        BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        String inputLine;
        while ((inputLine = input.readLine()) != null) {
            System.out.println(inputLine);
            System.out.println("Server: ");
            inputLine = input.readLine();
            output.println(inputLine);
            if (!inputLine.equals("exit")) {

            } else {
                break;
            }
        }
        output.close();
        input.close();
        clientSocket.close();
        serverSocket.close();
    }
}

The client is able to make a connection and send a message to the server.客户端能够建立连接并向服务器发送消息。 The server can also receive the messages sent by the client.服务器也可以接收客户端发送的消息。 The problem is that when the message is sent from the server, the client does not receive the message.问题是当消息从服务器发送时,客户端没有收到消息。 Here is my client socket code.这是我的客户端套接字代码。

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;


public class Client {
public static void main(String [] args) throws Exception
{
    BufferedReader input;
    PrintStream output;
    BufferedReader clientInput;
    try (Socket client = new Socket("127.0.0.1", 8085)) {
        input = new BufferedReader(new InputStreamReader(client.getInputStream()));
        output = new PrintStream(client.getOutputStream());
        clientInput = new BufferedReader(new InputStreamReader(System.in));
        String line;
        while(true)
        {
            System.out.println("Client: ");
            line = clientInput.readLine();
            output.println("Server: " + line );
            if(line.equals("quit"))
            {
                break;
            }
        }
    }
    input.close();
    clientInput.close();
    output.close();
}
}

Server side:服务器端:

public class Server {

    public static void main(String[] args) throws IOException {

        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(8085);
        } catch (IOException ex) {
            System.out.println("IO Error, " + ex);
            System.exit(1);
        }
        Socket clientSocket = null;
        System.out.println("Listening for incoming connections");
        try {
            clientSocket = serverSocket.accept();
        } catch (IOException ex) {
            System.out.println("Failed to accept connection " + ex);
            System.exit(1);
        }
        System.out.println("Connection Successful");
        System.out.println("Listening to get input");
        PrintStream output = new PrintStream(clientSocket.getOutputStream(), true);
        BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        String inputLine;
        while ((inputLine = input.readLine()) != null) {

            System.out.println("Client request: " + inputLine);

            String resp = "some response as you need";
            output.println(resp);
            System.out.println("Server response: " + resp);

            if (!inputLine.equals("exit")) {

            } else {
                break;
            }
        }
        output.close();
        input.close();
        clientSocket.close();
        serverSocket.close();
    }
}

Client side:客户端:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

public class Client {

    public static void main(String[] args) throws Exception {

        BufferedReader input;
        PrintStream output;
        BufferedReader clientInput;
        try (Socket client = new Socket("127.0.0.1", 8085)) {
            input = new BufferedReader(new InputStreamReader(client.getInputStream()));
            output = new PrintStream(client.getOutputStream());
            clientInput = new BufferedReader(new InputStreamReader(System.in));

            while (true) {

                String inputStr = clientInput.readLine();

                output.println(inputStr);
                System.out.println("Client: " + inputStr);

                if (inputStr.equals("quit")) {
                    break;
                }

                String serverResp = input.readLine();
                output.println("Server: " + serverResp);
            }
        }
    }
}

It is tested.它经过测试。

处理完输出流后刷新它们总是一个好主意,您发送的信息可能已缓冲。

The server is expecting an extra line from the client input here:服务器期待来自客户端输入的额外行:

while ((inputLine = input.readLine()) != null) {
    System.out.println(inputLine);
    System.out.println("Server: ");
    inputLine = input.readLine(); // <--- here

The client is not reading from the InputStream called input it gets when it connects to the server.当客户端连接到服务器时,它不会从名为inputInputStream 中读取数据。 It is only reading the local console input from clientInput .它仅从clientInput读取本地控制台输入。

In the while loop in Client.java you need something like this after the quit block to get the server's response:在 Client.java 中的 while 循环中,您需要在退出块之后的类似内容以获取服务器的响应:

System.out.println("Server: " + input.readLine());

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

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