JAVA学习总结十

第十八章 JAVA网络编程

  1. 网络分层模型
    OSI七层:物理层-数据链路层-网络层-传输层-会话层-表示层-应用层;
    TCP/IP四层:网络接口层-网络互联层-传输层-应用层;
  2. 网络端口号数量:65536个;
  3. 示例:
    客户端:
    public static void main(String[] args) {
    TODO Auto-generated method stub

    String message = JOptionPane.showInputDialog("你想对服务器说点啥?");
    Socket socket = null;
    BufferedWriter bw = null;
    try {
        //产生Socket对象,产生时告知IP地址和端口号
        socket = new Socket("127.0.0.1", 9527);
    
        //通过输出流操作,发送信息。
    

    socket.getOutputStream().write(message.getBytes());
    bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    bw.write(message);
    bw.flush();
    } catch (UnknownHostException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } finally{
    //关闭socket
    if(socket != null){
    try {
    socket.close();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    }

    }
    服务端:public class MessageThread extends Thread {
    private Socket socket;

    public MessageThread(Socket socket){
    this.socket = socket;
    }

    public void run(){
    // 从Socket里面取消息
    BufferedReader br = null;
    try {
    br = new BufferedReader(new InputStreamReader(socket.getInputStream()));//得到套接字的输入流与计算机输入流对接,再与阅读器对接;
    String str = br.readLine();
    System.out.println(“客户端说:” + str);
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } finally{
    if(br != null){
    try {
    br.close();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    if(socket != null){
    try {
    socket.close();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }

    }
    

    }
    服务端线程:
    public static void main(String[] args) {
    // TODO Auto-generated method stub

    ServerSocket server = null;
    
    
    try {
        // 产生一个ServerSocket对象
        server = new ServerSocket(9527);
        while (true) {
            System.out.println("开始监听......");
            // 开始监听,一旦得到消息就会返回给我们一个Socket对象
            Socket socket = server.accept();
            MessageThread th = new MessageThread(socket);
            th.start();
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        // 用完以后要关闭
        if (server != null) {
            try {
                server.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    

    }
    未完待续

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值