开发者社区> 问答> 正文

服务器可以向客户端发送消息,但不能从客户端接收消息

我有一个客户端服务器程序,其中servercoket将接受来自客户端的连接,并且客户端可以从服务器接收消息,反之亦然。客户端:

public class ChatClient {

private final String serverName;
private final int serverPort;
private Socket socket;
private OutputStream serverOut;
private InputStream serverIn;
private BufferedReader bufferedInputStream;
//private ArrayList<UserStatusListener> userListners = new ArrayList<UserStatusListener>();


private ChatClient(String serverName, int serverPort) {
    super();
    this.serverName = serverName;
    this.serverPort = serverPort;
}


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

    ChatClient client = new ChatClient("localhost", 8818);

    // Make sure serverboot is running and listenig first
    if (! client.connect()) {
        System.out.println("Connection Failed. Is ServerBoot running/listening?");
    }else {
        System.out.println("Connection succesful");
    client.login("guest");
    }

}


private boolean connect() {
    // TODO Auto-generated method stub
    try {
        this.socket = new Socket(serverName, serverPort); 

        // get streams
        this.serverOut = socket.getOutputStream();
        this.serverIn = socket.getInputStream();
        this.bufferedInputStream = new BufferedReader(new InputStreamReader(serverIn));

        return true;
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
        return false;
    }

}

private void login (String login) throws IOException {

    // send login to server
    try {

    String serverResponse = bufferedInputStream.readLine();
    System.out.println("Server response: " + serverResponse);

    while (bufferedInputStream.readLine() != null) {
        System.out.println(bufferedInputStream.readLine());
    }
String send = "Login : " + login;
        serverOut.write(send.getBytes());


    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }
}

片段构成服务器:

try {
                ServerSocket serverSocket = new ServerSocket(serverPortNumber);
                while (true) {
                    // Listen for incoming connections and craete connection with accept
                    System.out.println("Waiting for client connection.... on localhost port " + serverPortNumber
                            + ". \n Client connect via netcat localhost 8818");

                    Socket clientSocket = serverSocket.accept();// returns a client Socket object
                    System.out.println("Conenction established with " + clientSocket);


                    // Each new connection will be handled on a new thread and can run concurrenlty
                    ManageMultipleConnections multipleConnections = new ManageMultipleConnections(this, clientSocket);
                    clientList.add(multipleConnections);
                    multipleConnections.start();
                }

//获取客户端套接字输入流

clientInput = clientSocket.getInputStream();
        clientoutput = clientSocket.getOutputStream();

//写入客户端套接字

clientoutput.write((message).getBytes());

//尝试从客户端读取信息,但我们从未收到任何消息

BufferedReader br = new BufferedReader(new InputStreamReader(clientInput, ENCODING));
        String inputLine;
        String returnMessage;

        String msg = br.readLine();
        System.out.println(br.readLine());

        while ((inputLine = br.readLine()) != null && inputLine != "") {....do stuff

任何输入表示赞赏。

展开
收起
垚tutu 2019-12-12 09:22:31 1342 0
1 条回答
写回答
取消 提交回答
  • #include

    客户代码

    import java.io.*;
    import java.net.*;
    import java.util.*;
    
    
    public class Client {
       private String            serverIP = "127.0.0.1";
       private int               portNo   = 3030;
       private Socket            clientsock;
       private BufferedReader    keyRead;
       private OutputStream      ostream;
       private PrintWriter       pwrite;
       private InputStream       istream;
       private BufferedReader    receiveRead;
       private String            receiveMessage, sendMessage;
       private ArrayList<String> chatList;
    
       /**
        * Default constructor
        * 
        * @throws Exception
        */
    
       public Client() throws Exception {
           clientsock = new Socket(serverIP, portNo);
    
           // reading from keyboard (keyRead object)
           keyRead = new BufferedReader(new InputStreamReader(System.in));
    
           // chat save
           chatList = new ArrayList<String>();
    
           // sending to client (pwrite object)
           ostream = clientsock.getOutputStream(); 
           pwrite  = new PrintWriter(ostream, true);
    
           // receiving from server (receiveRead object)
           istream     = clientsock.getInputStream();
           receiveRead = new BufferedReader(new InputStreamReader(istream));
    
           System.out.println("Start the chitchat, type and press Enter key");
       } 
    
       /**
        * Runs the client, exchanging one-line messages with the Server,
        * collecting and displaying them until 'exit' is typed.
        * 
        * @throws Exception
        */
    
       public void run() throws Exception {
           boolean chatOn = true; 
           while (chatOn) {        
               sendMessage = keyRead.readLine();  // keyboard reading
               chatList.add("Me:  "+sendMessage); // save to array        
               if (sendMessage.equalsIgnoreCase("exit")) {
                   chatOn = false;
               }
    
               pwrite.println(sendMessage);      // sending to server
               pwrite.flush();                   // flush the data
    
               if (chatOn) {
                   if ((receiveMessage = receiveRead.readLine()) != null) {
                       // receive from server
                       System.out.println(receiveMessage);   // displaying at prompt
                       chatList.add("You: "+receiveMessage); // save to array
                   }
               }
           }               
       }
    
       /**
        * Stores the accumulated message log on disk
        * 
        * @throws Exception
        */
    
       public void chatSave() throws Exception {
           PrintStream print = new PrintStream(new File("log.txt"));
           for (String str : chatList)
               print.println(str);
           print.close();
       }
    
       /**
        * Main driver method that creates a Client object, runs it,
        * saves the chat and, when the run is complete, exits
        * 
        * @throws Exception
        */
    
       public static void main(String[] args) throws Exception {      
           Client thisClient = new Client();
           thisClient.run();
           thisClient.chatSave();
           System.exit(0);
       }                    
    }
    
    

    服务器代码-必须首先启动

    import java.io.*;
    import java.net.*;
    
    
    
    public class Server {
        private int            portNo = 3030;
        private ServerSocket   sersock;
        private Socket         clientsock;                        
        private BufferedReader keyRead;
        private OutputStream   ostream;
        private PrintWriter    pwrite;
        private InputStream    istream;
        private BufferedReader receiveRead;
        private String         receiveMessage, sendMessage;
    
        /**
         * Default constructor
         */
    
        public Server() {
            try{
                //init
                sersock = new ServerSocket(portNo);
                System.out.println("Server  ready for chatting");
                clientsock = sersock.accept( ); 
    
                // reading from keyboard (keyRead object)
                keyRead = new BufferedReader(new InputStreamReader(System.in));
    
                // sending to client (pwrite object)
                ostream = clientsock.getOutputStream(); 
                pwrite  = new PrintWriter(ostream, true);
    
                // receiving from server ( receiveRead  object)
                istream     = clientsock.getInputStream();
                receiveRead = new BufferedReader(new InputStreamReader(istream));
            } catch(Exception e) {
                return;
            }
        }
    
        /**
         * Runs the server, exchanging one-line messages with the Client,
         * displaying them until 'exit' is typed at the Client.
         */
    
        public void run() {
            boolean chatOn = true; 
            while(chatOn) {
                try {
                    if ((receiveMessage = receiveRead.readLine()) != null) {
                        System.out.println(receiveMessage);         
                    }         
                    if (receiveMessage.equalsIgnoreCase("exit")) {
                        chatOn = false;
                    }
    
                    if (chatOn) {
                        sendMessage = keyRead.readLine(); 
                        pwrite.println(sendMessage);             
                        pwrite.flush();
                    }
                } catch(Exception e) {
                    return;
                }
            }
        }
    
        /**
         * Main driver method that creates a Server object, runs it,
         * and, when the run is complete, exits
         */
    
        public static void main(String[] args) {
            Server thisServer = new Server();
            thisServer.run();
            System.exit(0);
        }                    
    }
    
    2019-12-12 09:23:06
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
如何运维千台以上游戏云服务器 立即下载
网站/服务器取证 实践与挑战 立即下载
ECS块储存产品全面解析 立即下载