소켓 프로그래밍

高洛峰
풀어 주다: 2016-10-20 11:33:18
원래의
1610명이 탐색했습니다.

먼저 가장 간단한 소켓 클라이언트 및 서버 예를 살펴보겠습니다.

Client

public class MyClient {
    public static void main(String[] args) {
        ObjectOutputStream oos = null;
        ByteArrayOutputStream bos = null;
        Socket client = null;
        try {
            People p = new People("2","yangyu","4","5","6");
            oos = new ObjectOutputStream(bos = new ByteArrayOutputStream()); //初始化object输出流
            oos.writeObject(p);  //将People对象写入输出流
            byte[] bytes = bos.toByteArray();  //获取People对象的byte数组(也就是序列化People)

            client = new Socket("127.0.0.1",20007);   //连接127.0.0.1的20007端口
            client.setSoTimeout(10000);   //设置超时时间

            client.getOutputStream().write(bytes);   //向server发送byte[]数组
            byte[] bytes1 = IOUtils.readFully(client.getInputStream(),18,false);  //获取server返回数据

            System.out.println(new String(bytes1));
            System.out.println(bytes1.length);

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                oos.close();
                bos.close();
                System.out.println(client.isClosed());
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
로그인 후 복사

Server

public class MyServer {
    public static void main(String[] args) {
        ServerSocket server = null;
        Socket client = null;
        ObjectInputStream ois = null;
        ByteArrayInputStream bis = null;

        try {
            server = new ServerSocket(20007);  //启动Socket server,监听20007端口
            client = server.accept(); //阻塞并等待接收客户端发送数据并生成client

            byte[] bytes = IOUtils.readFully(client.getInputStream(),-1,false);//获取客户端发送过来的数据
            bis = new ByteArrayInputStream(bytes);
            ois = new ObjectInputStream(bis);
            People people = (People) ois.readObject();//反序列化
            System.out.println("people name:"+people.getName());

            String res = "消息已经收到";
            client.getOutputStream().write(res.getBytes());//向客户端发送数据

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                bis.close();
                ois.close();
                client.close();
                server.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
로그인 후 복사

위는 클라이언트와 서버입니다. , 가장 간단한 예이지만 소켓 프로그래밍을 구현합니다.

서버가 항상 포트를 수신해야 하는 경우 루프만 하면 됩니다(server.accept()는 요청 대기를 차단합니다). 높은 동시성 응답의 경우 서버가 데이터 서비스를 처리합니다. 스레드에 넘겨지도록 합시다.


관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!