Java--网络编程(2)发送与接收

服务器端和客户端

客户端发消息给服务器端,服务器端接收到数据,将其数据显示在控制台上。

服务器端代码:

    //服务端
    @Test
    public void Server(){

        ServerSocket ss= null;
        Socket socket= null;
        InputStream is= null;
        ByteArrayOutputStream baos= null;
        try {
            //创建服务器端的ServerSocket,指明自己的端口号
            ss = new ServerSocket(6565);
            //调用accept(),表示接受来自于客户端的Socket
            socket = ss.accept();

            //获取输入流
            is = socket.getInputStream();
//        不建议这么写,可能会乱码
//        byte[] bytes=new byte[1024];
//        int len;
//        while((len=is.read(bytes))!=-1){
//            String str=new String(bytes,0,len);
//            System.out.print(str);
//        }

            //读取输入流中的数据
            baos = new ByteArrayOutputStream();
            byte[] buffer=new byte[5];
            int len;
            while((len=is.read(buffer))!=-1){
                baos.write(buffer,0,len);
            }
            System.out.println(baos.toString());
            System.out.println(socket.getInetAddress());


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(is!=null){

                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(ss!=null){
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(baos!=null){
                try {
                    baos.close();
                } catch (IOException e) {

                }
            }
        }
    }

客户端代码:

    //客户端
    @Test
    public void client() {

        Socket socket= null;
        OutputStream os= null;
        try {
            //创建Socket对象,指明服务器端的端口号和ip
            InetAddress inet=InetAddress.getByName("127.0.0.1");
            socket = new Socket(inet,6565);

            //获取输出流,用于获取数据
            os = socket.getOutputStream();
            os.write("你好".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            //关闭资源
            if(os!=null)
            try {
                os.close();
                } catch (IOException e) {
                 e.printStackTrace();
                }
            if(socket!=null)
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }

    }

1,服务器端创建ServerSocket,设置端口号
2,用Socket来接收客户端的连接
3,客户端必须要知道连接服务器端的ip及端口号
4,站在服务器端的角度,客户端的流是输出流;服务端的流是输入流。

发布了49 篇原创文章 · 获赞 0 · 访问量 1427

猜你喜欢

转载自blog.csdn.net/qq_43616001/article/details/104017423