首页 > 代码库 > socket编程1-echoclient

socket编程1-echoclient

talk()方法,不断读取用户从控制台输入的字符串,然后发送给EchoServer,再把EchoServer返回的字符串打印到控制台。如果用户输入字符串为“bye”,就结束与EchoServer的通信,关闭socket连接。

package Chapter1;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

public class EchoClient {
    String host = "localhost";
    int port = 8000;
    Socket socket;

    public static void main(String[] args) {
        try {
            new EchoClient().talk();
        } catch (Exception e) {
            System.out.println("访问异常");
        }
    }

    public EchoClient() {
        try {
            socket = new Socket(host, port);
            System.out.println("客户端程序开始访问");
            System.out.println("客户端talk,端口号:" + socket.getLocalPort());
        } catch (IOException e) {
            System.out.println("无法访问指定端口号 " + port);
        }
    }

    public void talk() {
            try {
                if (socket != null) {
                    System.out.println("----------------\n" + "请输入传输信息: ");
                    // 通过输入流读取到键盘输入字符
                    InputStreamReader sysin = new InputStreamReader(System.in);
                    BufferedReader localReader = new BufferedReader(sysin);
                    String msg = localReader.readLine();
                    // 使用输出流到服务器端socket
                    PrintWriter pw = getWriter(socket);
                    pw.println(msg);
                    // 通过输入流读取服务器端返回的内容
                    BufferedReader br = getReader(socket);
                    // 如果服务器端返回over,就关闭socket;如果未返回over就继续talk()
                    String response=br.readLine();
                    if (response.equals("over")||response.equals("echobye")) {
                        socket.close();
                        System.out.println("接收到服务器端返回\"over\",客户端关闭socket");
                    } else {
                        System.out.println("得到服务器端返回: " + response);
                        talk();
                    }
                }
            } catch (IOException e) {
                System.out.println("talk方法异常");
            }
        }

    private BufferedReader getReader(Socket socket) throws IOException {
        InputStream socketIn = socket.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(socketIn));
        return br;
    }

    private PrintWriter getWriter(Socket socket) throws IOException {
        OutputStream socketOut = socket.getOutputStream();
        PrintWriter pw = new PrintWriter(socketOut, true);
        return pw;
    }
}

socket编程1-echoclient