首頁  >  文章  >  类库下载  >  socket程式設計

socket程式設計

高洛峰
高洛峰原創
2016-10-20 11:33:181616瀏覽

首先讓我們來看看最簡單的socket client與server實例:

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

    }
}

以上一個Client和一個Server,最簡單的例子,但是體現socket程式設計。

如果需要Server服務端一直監聽端口,那麼只需要循環就可以(server.accept()會阻塞等待請求),至於需要高並發的響應,那麼Server對數據業務的處理交由線程池來做吧。


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
上一篇:JAVA WEB 作用域下一篇:JAVA WEB 作用域