java中简单的服务器和客户端字符串的传输

//服务器端

public class Client {
public static void main(String[] args) throws UnknownHostException, IOException {

    // TODO Auto-generated method stub
    Scanner input = new Scanner(System.in);
    try {
        while(true){
            //步骤1:创建Socket对象
            Socket s = new Socket("127.0.0.1",10086);
            System.out.println("客户端启动。。。");

            //步骤2:获取输入输出流
            OutputStream out = s.getOutputStream();
            InputStream in = s.getInputStream();

            //步骤3:处理数据

            System.out.print("客户端请输入消息:");
            String str = input.nextLine(); 
            out.write(str.getBytes());

            byte[] buf = new byte[1024];
            int len = in.read(buf);
            //String str = new String(buf);
            String str2 = new String(buf,0,len);

            System.out.println("客户端接收到信息:"+str2);
            if(str2.equals("exit")){
                System.out.println("客户端退出成功!!");
                break;
            }
            //步骤4:关闭资源
            out.close();
            in.close();
            s.close();
        }
    } catch (SocketException e) {
        // TODO Auto-generated catch block
        System.out.println("断开连接");
    }


}

}

//服务器端

public class Server {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
// 步骤1:创建ServerSocket,绑定端口
ServerSocket ss = new ServerSocket(10086);
// System.out.println(“服务器启动。。。”);
try {
while (true) {// 步骤2:监听Socket
Socket s = ss.accept();
// System.out.println(“监听到对象:”+s);

            // 步骤3:获取输入输出:
            InputStream in = s.getInputStream();
            OutputStream out = s.getOutputStream();

            // 步骤4:进行通讯,处理数据
            byte[] buf = new byte[1024];
            int len = in.read(buf);

            // String str = new String(buf);
            String str = new String(buf, 0, len);

            System.out.println("服务端接收到信息:" + str);
            if (str.equals("exit")) {
                System.out.println("服务端退出成功!!");
                break;
            }

            // String str2 = "你好啊,我是服务器端!";
            System.out.print("服务器端请输入消息:");
            String str2 = input.nextLine();
            out.write(str2.getBytes());

            // 步骤5:关闭资源
            in.close();
            out.close();
            s.close();
        }
    } catch (SocketException e) {
        // TODO Auto-generated catch block
        System.out.println("断开连接");

    }
}

}

你可能感兴趣的:(java中简单的服务器和客户端字符串的传输)