简体   繁体   中英

Sending and receiving with sockets

I am working on sending and receiving from clients and servers in java, and am stumped at the moment.

The client socket is to contact a server at "localhost" port 4321. The client will receive a string from the server and alternate spelling the contents of this string with the server. For example, given the string "Bye Bye", the client (which always begins sending the first letter) sends "B", receives "y", sends "e", receives " ", sends "B", receives "y", sends "e", and receives "done!", which is the string that either client or server will send after the last letter from the original string is received. After "done!" is transmitted, both client and server close their communications.

How would I go about getting the first string and then going back and forth sending and receiving letters that make the string, and when finished either send or get done!?

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Program2 {
    public static void goClient() throws UnknownHostException, IOException{
        String server = "localhost";
        int port = 4321;

        Socket socket = new Socket(server, port);
        InputStream inStream = socket.getInputStream();
        OutputStream outStream = socket.getOutputStream();
        Scanner in = new Scanner(inStream);
        PrintWriter out = new PrintWriter(outStream, true);

        String rec = "";
        if(in.hasNext()){
            rec = in.nextLine();
        }
        char[] array = new char[rec.length()];
        for(int i = 0; i < rec.length(); i++){
            array[i] = rec.charAt(i);
        }

        while(in.hasNext()){
            for(int x = 0; x < array.length + 1; x+=2){
                String str = in.nextLine();
                str = Character.toString(array[x]);
                out.println(str);
            }
            in.close();
            socket.close();
        }
    }
}

If you want a character at a time you can't use readLine(), right? I wouldn't use Scanner either. Just read a char at a time. You should be using a BufferedReader and a BufferedWriter.

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