网络编程只socket

来源:互联网 发布:mac进度条卡在一半黑屏 编辑:程序博客网 时间:2024/06/04 18:03

1、获取ip地址
1、getCanonicalHostName得到的是主机名,而getHostName得到的主机别名。
2、InetAddress.getByName()
InetAddress.getByAddress()
3、isReachable()
4、getLocalHost()
5、getHostAddress()
6、getHostName()

public class IPGet{    public static void main(String args[]) throws IOException {        //获取京东的ip地址,先输入地址        InetAddress ip=InetAddress.getByName("www.jd.com");        //判断是否能连接        System.out.println("京东"+ip.isReachable(2000));        //获取ip地址        System.out.println(ip.getHostAddress());        InetAddress local=InetAddress.getByAddress(new byte[]{127,0,0,1});        System.out.println(local.isReachable(5000));        System.out.println(local.getCanonicalHostName());        //实例化本机对象        InetAddress ipp=InetAddress.getLocalHost();        //打印本机ip        System.out.println(ipp.getHostAddress());        //打印本机名        System.out.println(ipp.getHostName());        System.out.println(ipp.getCanonicalHostName());     }}

2、URL解码编码
1、URLDecoder.decode()
2、URLEncoder.encode()

import java.io.UnsupportedEncodingException;import java.net.URLDecoder;import java.net.URLEncoder;public class UrlEncoding {    /**     * gbk  中文编码方式     * gb2321 国标     * utf-8 uncoide编码方式     * @param args     */    public static void main(String[] args) throws UnsupportedEncodingException {        // 将application/x-www-form-urlencoded字符串                // 转换成普通字符串                String keyWord = URLDecoder.decode(                 "%CE%D2%B0%AE%C4%E3%C7%D7%B0%AE%B5%C4%B9%C3%C4%EF", "gbk");                System.out.println(keyWord);                // 将普通字符串转换成                // application/x-www-form-urlencoded字符串                String urlStr = URLEncoder.encode(                    "我爱你亲爱的姑娘" , "GBK");                System.out.println(urlStr);    }}

3客户端和服务端
1、一个服务一个客户端

import java.net.*;import java.io.*;//客户端的代码public class Client{    public static void main(String[] args)        throws IOException    {        //建立一个客户端的scoket        Socket socket = new Socket("127.0.0.1" , 30000);           BufferedReader br = new BufferedReader(        new InputStreamReader(socket.getInputStream()));        String line = br.readLine();        System.out.println("data from service" + line);        br.close();        socket.close();    }}
import java.net.*;import java.io.*;//服务端的代码public class Server{    public static void main(String[] args)        throws IOException    {        //建立以个服务端的socket        ServerSocket ss = new ServerSocket(30000);        while (true)        {            //accept()接受客户端的请求,这是一个阻塞的方法            Socket s = ss.accept();            System.out.println("==================");            PrintStream ps = new PrintStream(s.getOutputStream());            ps.println("hello xiao zi");            ps.close();            s.close();        }    }}

2多线程客户端和服务端

0 0
原创粉丝点击