Java简单客户端服务器程序

Java简单客户端服务器程序

本文介绍了Java简单客户端服务器程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个简单的java代码来从服务器向客户端发送消息,客户端应该分别显示它。
代码为。

I have written a simple java code to send a message from server to client and the client should display it respectively.The codes are.

Client.java

Client.java

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
   public class Client {

    public static void main(String[] args) throws Exception {
        Socket client_socket = new Socket("localhost", 1235);
        BufferedReader reader = new BufferedReader(new InputStreamReader(client_socket.getInputStream()));
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(client_socket.getOutputStream()));
        String serverMsg = null;
        while ((serverMsg = reader.readLine()) != null) {
            System.out.println("Client: " + serverMsg);

        }
    }
}

java

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class Server {

    public static void main(String[] args) throws Exception {
        ServerSocket server_socket;
        server_socket = new ServerSocket(1235);
        while (true) {
            Socket mysocket = server_socket.accept();

            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(mysocket.getOutputStream()));
            BufferedReader reader = new BufferedReader(new InputStreamReader(mysocket.getInputStream()));
            writer.write("Hello omkar ");

            System.out.println("data sent");
        }
    }

}


现在的问题是当我运行这些代码,我得到在服务器端发送的消息数据,但客户端控制台是空白的。请帮我找到错误。

Issue:Now the problem is when i run these codes i get the message data sent on server side,but the client console is blank.Please help me find the mistake.

推荐答案

在服务器代码中,而不是使用BufferedWriter,使用PrintWriter。

In Server code rather than using BufferedWriter, use PrintWriter.

while (true) {
        Socket mysocket = server_socket.accept();

        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        BufferedReader reader = new BufferedReader(new InputStreamReader(mysocket.getInputStream()));
        out.println("Hello World!");

        System.out.println("data sent");
    }

这在我的系统上工作。试试这个。

This is working on my system. Try this.

这篇关于Java简单客户端服务器程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 22:04