java socket编程

一、url编码和url解码

  URLEncoder.encode(String s, String enc)  使用指定的编码机制将字符串转换为 application/x-www-form-urlencoded 格式 

  URLDecoder.decode(String s, String enc)  使用指定的编码机制对 application/x-www-form-urlencoded 字符串解码

    当URL地址里包含非西欧字符的字符串时,浏览器都会将这些非西欧字符串转换成application/x-www-form-urlencoded MIME 字符串,再提交給服务器。

二、TCP/IP协议

  计算机网络可以使多台计算机进行沟通,在通过ip和port可以确定一台计算机和要通信的地址后,就需要一个大家都遵守的网络协议来确定沟通的方式才能完成数据交换。

  TCP/IP协议总共分为四个层次:链路层、网络层、传输层、应用层

          

  UDP是无连接通信协议,即在数据传输时,数据的发送端和接收端不建立逻辑连接。简单来说,当一台计算机向另外一台计算机发送数据时,发送端不会确认接收端是否存在,就会发出数据,同样接收端在收到数据时,也不会向发送端反馈是否收到数据。

  TCP协议是面向连接的通信协议,即在传输数据前先在发送端和接收端建立逻辑连接,然后再传输数据,它提供了两台计算机之间可靠无差错的数据传输。在TCP连接中必须要明确客户端与服务器端,由客户端向服务端发出连接请求,每次连接的创建都需要经过“三次握手”。

  

三、代码事例

  ①编码和解码

public class Test {

    public static void main(String[] args) {
        try {
            String temp = URLEncoder.encode("我是中国人,我爱中国","utf-8");
            System.out.println(temp);
            String temp2 = URLDecoder.decode("%E6%88%91", "utf-8");
            System.out.println(temp2);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}

执行结果:
%E6%88%91%E6%98%AF%E4%B8%AD%E5%9B%BD%E4%BA%BA%EF%BC%8C%E6%88%91%E7%88%B1%E4%B8%AD%E5%9B%BD
我

  ②UDP协议

public class UDPSender {

    public static void main(String[] args) {
        DatagramSocket ds = null;
        try {
           ds = new DatagramSocket(8888);
           byte[] buffer = new byte[1024];
           DatagramPacket datagramPacket = new DatagramPacket(buffer, buffer.length, new InetSocketAddress("localhost", 8989));
           datagramPacket.setData("hello server".getBytes());
           ds.send(datagramPacket);
           
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            ds.close();
        }
    }
}

public class UDPReceiver {

    public static void main(String[] args) {
        DatagramSocket ds = null;
        try {
            ds = new DatagramSocket(8989);
            byte[] buffer = new byte[1024];
            DatagramPacket dp = new DatagramPacket(buffer,buffer.length);
            ds.receive(dp);
            String info = new String(dp.getData(),0,dp.getLength());
            int port = dp.getPort();
            String hostName = dp.getAddress().getHostName();
            System.out.println(hostName+":"+port+"/"+info);
            
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            ds.close();
        }
    }
}

  ③TCP协议

public class TCPServer {
    private int port;
    ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
    
    
    public TCPServer(int port){
        this.port = port;
    }
    
    public static void main(String[] args) {
        TCPServer server = new TCPServer(8888);
        server.startServer();
    }
    
    public void startServer(){
        ServerSocket serverSocket = null;
        Socket client = null;
        try {
            serverSocket = new ServerSocket(port);
            while(true){
                client = serverSocket.accept();
                fixedThreadPool.submit(new HandleTask(client));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                serverSocket.close();
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

class HandleTask implements Runnable{
    private Socket client ;
    public HandleTask(Socket client){
        this.client = client;
    }
    
    @Override
    public void run() {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = client.getInputStream();
            byte[] buffer = new byte[1024];
            int read = inputStream.read(buffer);
            System.out.println(new String(buffer,0,read));
            
            outputStream = client.getOutputStream();
            outputStream.write("服务器响应".getBytes());
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                inputStream.close();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
} 

public class TCPClient {
    private String host;
    private int port;
    
    public TCPClient(String host,int port){
        this.host = host;
        this.port = port;
    }

    public static void main(String[] args) {
        new TCPClient("localhost",8888).startClient();
    }
    
    public void startClient(){
        Socket socket = null;
        OutputStream outputStream = null;
        InputStream inputStream = null;
        try {
            socket = new Socket(host,port);
            outputStream = socket.getOutputStream();
            outputStream.write("hello server".getBytes());
            outputStream.flush();
            
            inputStream = socket.getInputStream();
            byte[] buffer = new byte[1024];
            int read = inputStream.read(buffer);
            System.out.println(new String(buffer,0,read));
            
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                socket.close();
                outputStream.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

  ④httpurl连接通信

  

public class UrlTest {

    public static void main(String[] args) {
        queryWeather("101010100");//查询北京的天气
        //queryInfo();
        
    }
    
    public static void queryWeather(String id){
        BufferedReader br = null;
        try {
            URL url = new URL("http://www.weather.com.cn/data/sk/"+id+".html");
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String resultInfo = "";
            while((resultInfo = br.readLine()) != null){
                System.out.println(resultInfo);
            }
            System.out.println(connection.getHeaderFields());
            System.out.println(connection.getContentType());
            System.out.println(connection.getResponseMessage());
            System.out.println(connection.getResponseCode());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    public static void queryInfo(){
        String param = "{\"page\":1,\"pagesize\":2,\"token\":\"token\"}";
        URL url;
        BufferedReader br = null;
        try {
            url = new URL("http://localhost/XXX/api/transfer/queryList");
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true); // 设置是否向connection输出,如果是post请求,参数要放在http正文内,因此需要设为true
            connection.setRequestProperty("Content-Type","application/json");
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(param.getBytes());
            outputStream.flush();
            outputStream.close();
            
            br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String resultInfo = "";
            while((resultInfo = br.readLine()) != null){
                System.out.println(resultInfo);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
    }
}

 

  

  

posted @ 2018-05-03 10:56  KyleInJava  阅读(241)  评论(0编辑  收藏  举报