首页 > 编程语言 >网络编程

网络编程

时间:2023-03-12 16:45:20浏览次数:28  
标签:java socket 编程 网络 System import InetAddress out

网络编程

ip地址

需导入import java.net.InetAddress;这个包

try{
    //查面本机地城
	InetAddress inetAddress1 = InetAddress.getByName("127.0.0.1");
    System.out.printIn(inetAddress1);
    InetAddress inetAddress3 = InetAddress.getByName("localhost");
    System.out.printIn(inetAddress3);
    InetAddress inetAddress4 = InetAddress.getLocalHost();
    System.out.printIn(inetAddress4);
//查询网站ip地址
    InetAddress inetAddress2 = InetAddress.getByName( "www,baidu,com");
    System.out.println(inetAddress2);
//常用方法
//System.out.println(inetAddress2.getAddress());
    System.out.println(inetAddress2.getCanonicalHostName()); //规范的名字
    System.out.println(inetAddress2.getHostAddress()); //ip
    System.out.println(inetAddress2.getHostName()); //域名,或者自己电脑的名字
}catch(UnknownHostException e){
    e.printStackTrace();
}

端口

InetSocketAddress socketAddress = new InetSocketAddress("127,0.0.1",8080);
InetSocketAddress socketAddress2 = new InetSocketAddress( "localhost", 8080);
System.out.println(socketAddress);
System.out.printIn(socketAddress2);
System.out.printIn(socketAddress.getAddress());
System.out.println(socketAddress.getHostName()); //地址
System.out.println(socketAddress.getPort()); //端口

TCP实现聊天

客户端

package com.zzy;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
// 客户端
public class tcpClient{
    public static void main(String[] args) {
        Socket socket = null;
        OutputStream os = null;
        try{
            //1,些知道服务器的地址,端口号
            InetAddress serverIP = InetAddress.getByName("127.0.0.1");
            int port = 9999;
            //2,创建一个socket连接
            socket = new Socket(serverIP,port);
            // 3,发这消息 IO流
            os = socket.getOutputStream();
            os.write("发送的内容".getBytes());
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket!= null) {
                try {
                    socket.close();
                }catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

服务端

package com.zzy;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
// 服务端
public class tcpServer {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            //建立一个地址
            serverSocket = new ServerSocket(9999);
            while (true) {
                //2. 等待客户端连接过水
                socket = serverSocket.accept();
                //3.读收客广端的消息
                is = socket.getInputStream();
                //管道流
                baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len;
                while ((len = is.read(buffer)) != -1) {
                    baos.write(buffer, 0, len);
                }
                System.out.println(baos.toString());
            }
        }catch(IOException e){
            e.printStackTrace();
        }finally{
            //关闭资源
            if (baos != null) {
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

UDP发送包

发送端

package com.zzy.udp;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class udpClient {
    public static void main(String[] args) throws Exception{
        //建立一个Socket
        DatagramSocket socket = new DatagramSocket();
        //建立一个包
        String msg = "这是一个包";
        InetAddress localhost = InetAddress.getByName("localhost");
        int port = 9090;
        //封装包,(数据,数据长度,发送地址与端口)
        DatagramPacket packet = new DatagramPacket(msg.getBytes(),0,msg.getBytes().length,localhost,port);
        //发送包
        socket.send(packet);
        //关闭流
        socket.close();
    }
}

接收端

package com.zzy.udp;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class udpReceive {
    public static void main(String[] args) throws Exception{
    //开放端口
    DatagramSocket socket = new DatagramSocket(9090);
    //接收数据包
    byte[] buffer = new byte[1024];
    DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
    socket.receive(packet);//阻塞接收
    //输出数据包
    System.out.println(packet.getAddress().getHostAddress());
    System.out.println(new String(packet.getData(),0,packet.getLength()));
    //关闭流
    socket.close();
    }
}

URL

例:www.baidu.com

协议://ip地址:端口/项目名/资源

标签:java,socket,编程,网络,System,import,InetAddress,out
From: https://www.cnblogs.com/zhao19811103/p/17208441.html

相关文章

  • 实验1Python开发环境使用和编程初体验
    实验任务一:task1_1:实验源码:Python3.10.7(tags/v3.10.7:6cc6b13,Sep52022,14:08:36)[MSCv.193364bit(AMD64)]onwin32Type"help","copyright","credi......
  • API和Lambda函数式编程思想
    Arrays工具类1.Arrays.toString()该方法可以将对应数组内容以字符串形式输出2.Arrays.sort(int[])该方法对int数组内容进行选择排序原理:for(intx=0;x<arr.......
  • 编程中常见的 Foo 是什么意思?
    “Foo”是一个编程中经常使用的占位符,它没有特定的含义,只是作为一个通用的标识符来使用,这种用法类似于数学中的"x"或"y"。这个词最初可能源于20世纪60年代MIT的人工智能......
  • 743. 网络延迟时间 (Medium)
    问题描述743.网络延迟时间(Medium)有n个网络节点,标记为1到n。给你一个列表times,表示信号经过有向边的传递时间。times[i]=(uᵢ,vᵢ,wᵢ),其中uᵢ是源节......
  • 并发编程-信号量
    importrandomimporttimefromthreadingimportThread,Semaphoresm=Semaphore(5)'''semaphore信号量可以通过内置计数器来控制同时运行线程的数量每当调用......
  • Ubuntu 20.04 挂载局域网络共享硬盘
    创建挂载目录mkdir/media/nas创建认证文件。若无密码可以忽略这一步。sudovim/root/.examplecredentials按照以下格式写入用户名密码:username=example_usern......
  • C++11异步编程(std::async, std::future, std::packaged_task, std::promise)
    文章目录​​1.std::future概述含义​​​​2.std::future​​​​2.std::packaged_task​​​​2.std::promise​​1.std::future概述含义C++0x提供了future和promise来简......
  • 【编辑器】常用编程环境使用感受20190804
    一、编辑器1、Vim/Emase又被称之为神器:编辑器之神vs神之编辑器学习使用成本高and定义所有功能2、Sublime/Vscode/Atom现在编辑器,有以下特点:跨平台,颜值高,性能佳3、Note......
  • 学习ASP.NET Core Blazor编程系列二十八——JWT登录(3)
    学习ASP.NETCoreBlazor编程系列文章之目录学习ASP.NETCoreBlazor编程系列一——综述学习ASP.NETCoreBlazor编程系列二——第一个Blazor应用程序(上)学习A......
  • C#高级编程2
        C#快速构建代码块简写功能总结表格简写功能示例prop创建属性代码块publicintMyProperty{get;set;}cw创建对Console.WriteL......