java网络传输学习

import java.net.InetAddress;
import java.net.UnknownHostException;

public class source {

    public static void main(String[] args) throws UnknownHostException {
        InetAddress localHost = InetAddress.getLocalHost();
        System.out.println(localHost);//主机名和IP地址
        InetAddress byName = InetAddress.getByName("PC-20230129EACF");
        System.out.println(byName);
        InetAddress byName1 = InetAddress.getByName("www.baidu.com");//获取百度域名的的对象
        System.out.println(byName1);//需要联网访问百度的对象
        String hostAddress = localHost.getHostAddress();
        System.out.println(hostAddress);//获得主机对应地址
        String hostName = localHost.getHostName();
        System.out.println(hostName);


    }
}

运行结果如下

PC-20230129EACF/192.168.43.87
PC-20230129EACF/192.168.43.87
www.baidu.com/14.119.104.254
192.168.43.87
PC-20230129EACF

服务器读写

package source;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class serversocket {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket=new ServerSocket(999);
        Socket socket=serverSocket.accept();//等待其连接
//        Socket socket1 = new Socket(InetAddress.getLocalHost(), 999);
        InputStream inputStream = socket.getInputStream();
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("hello,jack".getBytes(StandardCharsets.UTF_8));
        socket.shutdownOutput();
        byte [] buf=new byte[1024];
        int a=0;
        while ((a=inputStream.read(buf))!=-1){
            System.out.println(new String(buf,0,a));
        }
        outputStream.close();
        inputStream.close();
        socket.close();
        serverSocket.close();
    }
}

客服端读写

package source;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;

public class server {
    public static void main(String[] args) throws IOException {
        Socket socket1 = new Socket(InetAddress.getLocalHost(), 999);
//        System.out.println(socket1.getClass());
        OutputStream outputStream = socket1.getOutputStream();
        InputStream inputStream = socket1.getInputStream();
        int read=0;
        byte []buf=new byte[1024];
        while ((read=inputStream.read(buf))!=-1){
            System.out.println(new String(buf,0,read));
        }
        outputStream.write("hello,world".getBytes(StandardCharsets.UTF_8));
        socket1.shutdownOutput();
        inputStream.close();
        outputStream.close();
        socket1.close();
    }

}

你可能感兴趣的:(java,网络,学习)