创建连接并模拟服务器和客户端

package com.mepu;

import org.junit.Test;

import java.io.*;
import java.net.*;

/**
 * @author: 艾康
 * @date: 2020/1/1 16:01
 * @description: TODO
 * @modifiedBy:
 * @version: 1.0
 */
public class IntelTest {
    //实例化
    @Test
    public void test1() throws UnknownHostException {
        //获通过域名获取主机
        InetAddress byName = InetAddress.getByName("www.baidu.com");
        InetAddress byName1 = InetAddress.getByName("192.168.0.1");
        InetAddress byName2 = InetAddress.getByName("127.0.0.1");
        InetAddress localhost = InetAddress.getByName("localhost");
        //常用方法
        //获取域名
        String hostName = byName.getHostName();
        //获取主机地址
        String hostAddress = byName.getHostAddress();
    }

    /**
     * 服务器模拟
     */
    @Test
    public void server() {
        ServerSocket serverSocket = null;
        Socket accept = null;
        InputStream stream = null;
        ByteArrayOutputStream outputStream = null;
        try {
            //建立端口号
            serverSocket = new ServerSocket(8899);
            //创建Socket
            accept = serverSocket.accept();
            //获取输入流对象
            stream = accept.getInputStream();
            //ByteArrayOutputStream解决中文被拆分问题
            byte[] b = new byte[1024];
            outputStream = new ByteArrayOutputStream();
            int len;
            while ((len = stream.read(b)) != -1) {
                //数据存入ByteArrayOutputStream
                outputStream.write(b,0,len);
            }
            //输出
            System.out.println(outputStream.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                //关闭流
                outputStream.close();
                stream.close();
                accept.close();
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //客户端
    @Test
    public void client(){
        Socket socket = null;
        OutputStream outputStream = null;
        try {
            //设置域名
            InetAddress byName = InetAddress.getByName("127.0.0.1");
            //创建Socket
            socket = new Socket(byName, 8899);
            //获取输出流
            outputStream = socket.getOutputStream();
            outputStream.write("你好!我是客户端".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                //关闭流
                outputStream.close();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/aikang525/p/12129343.html