Ascii on TCP socket

后端 未结 3 1484
孤独总比滥情好
孤独总比滥情好 2021-01-14 08:39

Anyone could pass me an example of sending Ascii msg over TCP?(couldnt find example on the net)

thanks,

ray.

3条回答
  •  心在旅途
    2021-01-14 09:09

    Here's an example of writing to and reading from an echoing server.

    A simplified excerpt:

        Socket echoSocket = null;
        PrintWriter out = null;
        BufferedReader in = null;
    
        try {
            echoSocket = new Socket("taranis", 7);
            out = new PrintWriter(echoSocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(
                                        echoSocket.getInputStream()));
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: taranis.");
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for "
                               + "the connection to: taranis.");
            System.exit(1);
        }
    
    BufferedReader stdIn = new BufferedReader(
                                   new InputStreamReader(System.in));
    String userInput;
    
    while ((userInput = stdIn.readLine()) != null) {
        out.println(userInput);
        System.out.println("echo: " + in.readLine());
    }
    

提交回复
热议问题