服务器/客户端不通过套接字[Java]发送或接收数据? [英] Server/client not sending or receiving data through socket [Java]?

查看:74
本文介绍了服务器/客户端不通过套接字[Java]发送或接收数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设置了一个服务器/客户端聊天程序.应该发生的事是这样一种服务器设置,该服务器可以A)从客户端读取,A2)从客户端读取读取的内容并将其发送给所有其他客户端,或者B)从控制台获取输入以写入客户端.客户端可以从服务器读取并要求其发送消息(也可以从控制台读取消息).

I set up a server/client chat program. What's supposed to happen is a server is setup that can A) read from clients, A2) take what's read from clients and send it to all other clients or B) take input from the console to write to clients. The clients can read from the server and ask it to send messages (which are also read from the console).

共有三个文件:

  • Maim.java(稍后将用于其他目的;现在只是Server类的样板)
  • Host.java(服务器)
  • Client.java(客户端)

您应该打开一个终端并运行Maim来启动服务器,然后打开另一个终端并运行Client来运行客户端.但是,两者之间没有传输消息,这很奇怪,因为

You're supposed to open one terminal and run Maim which starts a server, then open another terminal and run Client, which runs the client. However, messages are NOT being transmitted between the two, which is odd because

  1. 流和套接字已成功建立,并且
  2. 如果您允许发送'null's(即:((message = in.readLine())vs.((message = in.readLine())!= null))),则将发送'null's.但是只有"null",没有别的.

无论如何,这是代码:

Maim:

    import java.io.*;
    import java.util.*;
    public class Maim {
        static final int port = 9001;
        static final String localhost = "localhost";
        public static void main(String[] args) throws IOException {
            Scanner nameReader = new Scanner(System.in);
            System.out.println("What will your name be ? (Currently this        feature is unused)");
                new Host(nameReader.nextLine()).setUpServer();
       }    
    }

主机:

    import java.net.*;
    import java.io.*;
    import java.util.*;
    public class Host {
        Socket clientReader;
        String name;
        private ArrayList<ClientReader> clients;
        public Socket getSocket() {
            return clientReader;
        }
        public Host(String name) {
            this.name = name;
        }
        public void setUpServer(){
            clients = new ArrayList<ClientReader>();
            try {
                ServerSocket server =  new ServerSocket(Maim.port);
                System.out.println("Server set up without fail. Now awaitting clients.");
                this.clientReader(server);
            } catch (IOException e) {
                System.out.println("Failure setting up server on host's network.");
                e.printStackTrace();
            }
        }
        public void clientReader(ServerSocket server) {
            try {
                while (true) {
                    clientReader = server.accept();
                    ClientReader newReader = new ClientReader(clientReader);
                    clients.add(newReader);
                    Thread newClientThread = new Thread(newReader);
                    newClientThread.start();
                    Thread newHostThread = new Thread(new ClientWriter());
                    newHostThread.start();
                    System.out.println("New client connection");
                }
            } catch (IOException e) {
                System.out.println("Failure to connect to client.");
                e.printStackTrace();
            }
        }
        public void sendAll(String message) {
            try {
                for (ClientReader client: clients) {
                    PrintWriter writerToClient = new PrintWriter(client.getSocket().getOutputStream());
                    writerToClient.println(message);
                }
            } catch (IOException e) {
                System.out.println("Error sending message " + message + " .");
                e.printStackTrace();
            }
        }
        public class ClientReader implements Runnable {
            private BufferedReader consoleReader;
            private Socket server;
            public ClientReader(Socket clientSocket) {
                try {
                    server = clientSocket;
                    consoleReader = new BufferedReader(new InputStreamReader(this.server.getInputStream()));
                    consoleReader.ready();
                    System.out.println("Succesfully received client's stream");
                } catch(IOException e) {
                    System.out.println("Error getting input stream from host.");
                    e.printStackTrace();
                }
            }
            public Socket getSocket() {
                return this.server;
            }
            public void run() {
                String newMessage = new String();
                try {
                    while ((newMessage = this.consoleReader.readLine()) != null) {
                        System.out.println(newMessage);
                        sendAll(newMessage);
                    }
                } catch(IOException e) {
                    System.out.println("Error sending client message to clients.");
                    e.printStackTrace();
                }
            }        

        }
        public class ClientWriter implements Runnable {
            private PrintWriter consoleWriter;
            public void run() {
                try {
                    String newMessage;
                    Scanner consoleReader = new Scanner(System.in);
                    while (!(newMessage = consoleReader.nextLine()).equals("\n")) {
                        System.out.println(newMessage);
                        sendAll(newMessage);
                    }
                } catch(Exception e) {
                    System.out.println("Error sending host's message to clients.");
                    e.printStackTrace();
                }
            }
        }
    }

客户:

    import java.net.*;
    import java.io.*;
    import java.util.*;
    public class Client {
        Socket host;
        PrintWriter writeToHost;
        BufferedReader readFromHost;
        public static void main(String[] args) {
            new Client().connectToHost();
        }
        public void connectToHost() {
            try { 
                this.host = new Socket(Maim.localhost,Maim.port);
                this.writeToHost = new PrintWriter(host.getOutputStream());
                this.readFromHost = new BufferedReader(new InputStreamReader(host.getInputStream()));
                this.readFromHost.ready();
                System.out.println("Connected to host successfully.");
                this.go();
            } catch (IOException e) {
                System.out.println("Error connecting to host's server.");
                e.printStackTrace();
            }
        }
        public void go() {
            Thread innerReader = new Thread(new InnerReader());
            innerReader.start();
            Thread innerWriter = new Thread(new InnerWriter());
            innerWriter.start();
        }
        public class InnerReader implements Runnable {
            public void run() {
                try {
                    String message = new String();
                    while ((message = readFromHost.readLine()) != null) {
                        System.out.println(message);
                    }
                } catch(Exception e) {
                    System.out.println("Gotta Catch 'Em All! Insert proper exception string later");
                    e.printStackTrace();
                }
            }
        }
        public class InnerWriter implements Runnable {
            public void run() {
                try {
                    Scanner consoleReader = new Scanner(System.in);
                    String newMessage = new String();
                    while (!(newMessage = consoleReader.nextLine()).equals("\n")) {
                        System.out.println(newMessage);
                        writeToHost.println(newMessage);
                    }
                } catch (Exception e) {
                    System.out.println("Im so tired and Java's consistent boilerplate is so mind-numbing i can't even synthesize a proper sentence here");
                    e.printStackTrace();
                }
            }
        }
    }

感谢您的帮助!

推荐答案

您需要在写入PrintWriter后刷新它:

You need to flush the PrintWriter after writing to it:

writerToClient.flush();

这将放在HostsendAll中.

这篇关于服务器/客户端不通过套接字[Java]发送或接收数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆