Java中TCP和UDP

阅读更多
1. 网页内容获取

Url1.java

import java.net.URL;
public class Url1{
    public static void main(String[] args) throws Exception{
        URL url = new URL("http://java.sun.com:80/docs/books/tutorial/index.html#DOWN");
        String protocol = url.getProtocol();
        String host = url.getHost();
        String file = url.getFile();
        int port = url.getPort();
        String ref = url.getRef();
        System.out.println(protocol + ", " + host + ", " + file + ", " + port + ", " + ref);
    }
}
运行结果:
http, java.sun.com, /docs/books/tutorial/index.html, 80, DOWN


将html内容保存成txt文件格式

UrlConnection1.java

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
public class UrlConnection1{
    public static void main(String[] args) throws Exception{
        URL url = new URL("http://www.infoq.com");
        URLConnection conn = url.openConnection();
        InputStream is = conn.getInputStream();
        OutputStream os = new FileOutputStream("c:\\infoq.txt");
        byte[] buffer = new byte[2048];
        int length = 0;
        while(-1 != (length = is.read(buffer, 0, buffer.length))){
            os.write(buffer, 0, length);
        }
        is.close();
        os.close();
    }
}


另一种方式将html保存到成本地html

UrlConnection2.java

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
public class UrlConnection2 {
    public static void main(String[] args) throws Exception{
        URL url = new URL("http://www.csdn.net");
//        URLConnection conn = url.openConnection();
//        InputStream is = conn.getInputStream();
        InputStream is = url.openStream();
        OutputStream os = new FileOutputStream("c:\\infoq.html");
        byte[] buffer = new byte[2048];
        int length = 0;
        while(-1 != (length = is.read(buffer, 0, buffer.length))){
            os.write(buffer, 0, length);
        }
        is.close();
        os.close();
    }
}


打印www.sohu.com的源代码

UrlConnection3.java

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
public class UrlConnection3{
    public static void main(String[] args) throws Exception{
        URL url = new URL("http://www.sohu.com");
        BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
        String line = null;
        while(null != (line = br.readLine())){
            System.out.println(line);
        }
        br.close(); 
    }
}


读取http://www.baidu.com的网页源代码

UrlConnection4.java

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
class Win extends JFrame implements ActionListener, Runnable{
    JButton button;
    URL url;
    JTextField text;
    JTextArea area;
    byte b[] = new byte[118];
    Thread thread;
    public Win(){
        text = new JTextField(20);
        area = new JTextArea(12, 12);
        button = new JButton("确定");
        button.addActionListener(this);
        thread = new Thread(this);
        JPanel p = new JPanel();
        p.add(new JLabel("输入网址:"));
        p.add(text);
        p.add(button);
        Container con = this.getContentPane();
        con.add(new JScrollPane(area), BorderLayout.CENTER);
        con.add(p, BorderLayout.NORTH);
        setBounds(60, 60, 400, 300);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    public void actionPerformed(ActionEvent e){
        if (!(thread.isAlive())){
            thread = new Thread(this);
        }
        try{
            thread.start();
        }
        catch (Exception ee){
            JOptionPane.showMessageDialog(this, "我正在读取,请稍后", "提示信息", JOptionPane.ERROR_MESSAGE);
        }
    }
    public void run(){
        try{
            int n = -1;
            area.setText(null);
            url = new URL(text.getText().trim());
            InputStream in = url.openStream();
            while ((n = in.read(b)) != -1){
                String s = new String(b, 0, n);
                area.append(s);
            }
        }
        catch (MalformedURLException e1){
            text.setText("" + e1);
            return;
        }
        catch (IOException e1){
            text.setText("" + e1);
            return;
        }
    }
}
public class UrlConnection4{
    public static void main(String args[]){
        new Win();
    }
}


InetAddressTest.java

import java.net.InetAddress;
public class InetAddressTest{
    public static void main(String[] args) throws Exception{
        InetAddress address = InetAddress.getLocalHost();
        System.out.println(address);
        address = InetAddress.getByName("www.sohu.com");
        System.out.println(address);
    }
}


2. 套接字(Socket)实现TCP

TcpServer.java

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServer{
    public static void main(String[] args) throws Exception{
        ServerSocket ss = new ServerSocket(5000);
        Socket socket = ss.accept();
        InputStream is = socket.getInputStream();
        OutputStream os = socket.getOutputStream();
        byte[] buffer = new byte[200];
        int length = is.read(buffer);
        System.out.println(new String(buffer, 0 ,length));
//        int length = 0;
//        while(-1 != (length = is.read(buffer,0, buffer.length))){
//            String str = new String(buffer, 0, length);
//            System.out.println(str);
//        }
        os.write("welcome".getBytes());
        is.close();
        os.close();
        socket.close();
    }
}


TcpClient.java

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class TcpClient{
    public static void main(String[] args) throws Exception{
        Socket socket = new Socket("127.0.0.1", 5000);
        InputStream is = socket.getInputStream();
        OutputStream os = socket.getOutputStream();
        os.write("hello world".getBytes());
        byte[] buffer = new byte[200];
        
        int length = is.read(buffer);
        System.out.println(new String(buffer, 0 ,length));
//        int length = 0;
//        while(-1 != (length = is.read(buffer,0, buffer.length))){
//            String str = new String(buffer, 0, length);
//            System.out.println(str);
//        }
        is.close();
        os.close();
        socket.close();
    }
}
运行结果:
Server端:hello world
Client端:welcome


3. 实现实时通信

ServerInputThread.java

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
public class ServerInputThread extends Thread{
    private Socket socket;
    public ServerInputThread(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run(){
        try{
            InputStream is = socket.getInputStream();
            while(true){
                byte[] buffer = new byte[1024];
                int length = is.read(buffer);
                String str = new String(buffer, 0, length);
                System.out.println(str);
            }
        }
        catch (IOException e){
            e.printStackTrace();
        }
    }
}


ServerOutputThread.java

package code17;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
public class ServerOutputThread extends Thread{
    private Socket socket;
    public ServerOutputThread(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run(){
        try{
            OutputStream os = socket.getOutputStream();
            while(true){
                BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
                String line = reader.readLine();
                os.write(line.getBytes());
            }
        }
        catch (IOException e){
            e.printStackTrace();
        }
    }
}


ClientInputThread.java

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
public class ClientInputThread extends Thread{
    private Socket socket;
    public ClientInputThread(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run(){
        try{
            InputStream is = socket.getInputStream();
            while(true){
                byte[] buffer = new byte[1024];
                int length = is.read(buffer);
                String str = new String(buffer, 0, length);
                System.out.println(str);
            }
        }
        catch (IOException e){
            e.printStackTrace();
        }
    }
}


ClientOutputThread.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
public class ClientOutputThread extends Thread{
    private Socket socket;
    public ClientOutputThread(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run(){
        try{
            OutputStream os = socket.getOutputStream();
            while (true){
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(System.in));
                String line = reader.readLine();
                os.write(line.getBytes());
            }
        }
        catch (IOException e){
            e.printStackTrace();
        }
    }
}


发送消息给客户端,接收客户端的消息

MainServer.java

import java.io.IOException;
import java.net.Socket;
public class MainClient{
    public static void main(String[] args) throws Exception, IOException{
        Socket socket = new Socket("127.0.0.1", 4000);
        new ClientInputThread(socket).start();
        new ClientOutputThread(socket).start();
    }
}


发送消息给服务器端,接收服务器端的消息

MainClient.java

import java.net.ServerSocket;
import java.net.Socket;
public class MainServer{
    public static void main(String[] args) throws Exception{
        ServerSocket serverSocket = new ServerSocket(4000);
        while(true){
            Socket socket = serverSocket.accept();
            //启动读写线程
            new ServerInputThread(socket).start();
            new ServerOutputThread(socket).start();
        }
    }
}


4. 无连接的数据报UDP

UdpTest1.java

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UdpTest1{
    public static void main(String[] args) throws Exception{
        DatagramSocket socket = new DatagramSocket();
        String str = "hello world";
        DatagramPacket packet = new DatagramPacket(str.getBytes(),
                str.length(), InetAddress.getByName("localhost"), 7000);
        socket.send(packet);
        byte[] buffer = new byte[1000];
        DatagramPacket packet2 = new DatagramPacket(buffer,100);
        socket.receive(packet2);
        System.out.println(new String(buffer, 0, packet2.getLength()));
        socket.close();
    }
}
运行结果:
启动UdpTest2.java后显示:
hello world


UdpTest2.java

import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UdpTest2{
    public static void main(String[] args) throws Exception{
        DatagramSocket socket = new DatagramSocket(7000);
        byte[] buffer = new byte[1000];
        DatagramPacket packet = new DatagramPacket(buffer, 1000);
        socket.receive(packet);
        System.out.println(new String(buffer, 0, packet.getLength()));
        String str = "welcome";
        DatagramPacket packet2 = new DatagramPacket(str.getBytes(),
                str.length(), packet.getAddress(), packet.getPort());
        socket.send(packet2);
        socket.close();
    }
}
运行结果:
启动UdpTest1.java后显示:
welcome

你可能感兴趣的:(java)