简体   繁体   中英

Java Socket Sending Data

I have created two classes one server and client, I send data via the socket input and output stream however cant send multiple messages?

Server:

public class SOK_1_SERVER {

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

        SOK_1_SERVER Sever = new SOK_1_SERVER();
        Sever.run();
    }

    private void run() throws Exception {
        ServerSocket SRVSOCK = new ServerSocket(444);
        //Waits both client and server to accept and we return 
        //a socket
        Socket SOCK = SRVSOCK.accept();
        //Once accepted 
        InputStreamReader isr = new InputStreamReader(SOCK.getInputStream());
        BufferedReader br = new BufferedReader(isr);

        String message = br.readLine();
        System.out.println("I read: " + message + "from Client");

        if(message != null)
        {
            //Sending message back to client 
            PrintStream ps = new PrintStream(SOCK.getOutputStream());
            ps.println("Message Received");
            ps.println("Send from Server");
        }
    }
}

Client

public class SOK_1_CLIENT {

    public static void main(String[]args) throws Exception
    {
        SOK_1_CLIENT client = new SOK_1_CLIENT();
        client.run();
    }

    private void run() throws Exception {
        Socket SOCK = new Socket("localhost",444);
        PrintStream ps = new PrintStream(SOCK.getOutputStream());
        ps.println("Hello to Server from client");

        InputStreamReader ir = new InputStreamReader(SOCK.getInputStream());
        BufferedReader br = new BufferedReader(ir);

        String message = br.readLine();

        System.out.println(message);

    }

}

It only outputs message received however I think its because I need to have a loop to keep checking for new messages however not sure as I have just started this looking into sockets.

In your client class, you need to iterate the bufferedReader .

instead of

 String message = br.readLine();

 System.out.println(message);

use this,

 String message ;
 while((message = br.readLine())!=null) {
     System.out.println(message);
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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