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

Posted aikang525

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了创建连接并模拟服务器和客户端相关的知识,希望对你有一定的参考价值。

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();
            }
        }
    }
}

以上是关于创建连接并模拟服务器和客户端的主要内容,如果未能解决你的问题,请参考以下文章

Socket编程(在控制台模拟聊天功能)

java socket客户端模拟测试高并发服务器

[Python Study Notes] Socket模拟ssh并记录遇到的问题

智能预判 (六: 服务端战斗 模拟)

有没有办法使用相同的布局动态创建片段并向它们显示数据?

Node.js创建服务器和模拟客户端请求