java网络编程

TCP协议原理案例

package inet;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 服务器端
 */

public class EchoServeDemo {
    public static void main(String[] args){
        //创建一个服务器端的Socket(0-1024)一般不用,因为是一些其他公司产品的端口
        try {
            ServerSocket server = new ServerSocket(6666);
            System.out.println("服务器已启动,等待客户端的连接...");

            //等待客户端连接,会造成阻塞,如果客户端连接成功,立即返回一个Socket对象
            Socket socket = server.accept();
            System.out.println("客户端连接成功"+server.getInetAddress().getHostName());
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(socket.getInputStream())
            );
            //通过输入流读取网络数据
            String info = br.readLine();
            System.out.println(info);
            //获取输出流,向客户端返回消息
            PrintStream ps = new PrintStream(
                    new BufferedOutputStream(socket.getOutputStream()));
            ps.println("echo "+info);
            ps.flush();
            //关闭
            ps.close();
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

package inet;

import java.io.*;
import java.net.Socket;

/**
 * 客户端
 */
public class EchoClientDemo {
    public static void main(String[] args) {
        //创建一个socket对象,指定要连接的服务器
        try {
            Socket socket = new Socket("localhost",6666);
            //获取socket的输入项
            PrintStream ps = new PrintStream(
                    new BufferedOutputStream(socket.getOutputStream()));
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(socket.getInputStream()));
            ps.println("hello,my name is xiaoming.");
            ps.flush();
            //读取服务器返回的数据
            String info = br.readLine();
            System.out.println(info);
            ps.close();
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

服务器同时处理多个客户端实例

package inet;

import com.sun.source.tree.NewArrayTree;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

//服务器同时处理多个客户端实例
public class MultiServeDemo {
    public static void main(String[] args) {
        ExecutorService es = Executors.newFixedThreadPool(3);//通过线程控制多个客户端
        System.out.println("服务器已启动,等待客户端链接...");
        try {
            ServerSocket server = new ServerSocket(6666);
            while(true){
                Socket socket = server.accept();
                System.out.println(socket.getInetAddress().getHostName());
                MyRunnable mr = new MyRunnable(socket);
                es.execute(mr);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

/**
 * 用来处理客户端请求的线程
 */
class MyRunnable implements Runnable{
    private Socket socket;

    public MyRunnable(Socket socket){
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintStream ps = new PrintStream(new BufferedOutputStream(socket.getOutputStream()));
            String info = br.readLine();
            System.out.println(info);
            ps.println("收到,返回给你信息"+info);
            ps.flush();
            ps.close();
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

即时聊天案例

相关类

package communication;

import java.io.Serializable;

/**
 * 消息包,需要进行对象流处理,所以要继承Serializable标记接口
 */
public class Message implements Serializable {

    private String from;//消息来源
    private String to;//消息发送目的地
    private String info;//消息内容
    private int type;//消息内容

    public Message() {
    }

    public Message(String from, String to, String info, int type) {
        this.from = from;
        this.to = to;
        this.info = info;
        this.type = type;
    }

    public String getFrom() {
        return from;
    }

    public void setFrom(String from) {
        this.from = from;
    }

    public String getTo() {
        return to;
    }

    public void setTo(String to) {
        this.to = to;
    }

    public String getInfo() {
        return info;
    }

    public void setInfo(String info) {
        this.info = info;
    }

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }
}

public class MessageType {
    public static final int TYPE_LOGIN = 0x01;
    public static final int TYPE__SEND = 0X02;
}

服务器端

package communication;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Vector;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 服务器端
 */
public class Server {
    public static void main(String[] args) {
        //保存客户端处理的线程
        Vector<UserThread> vector = new Vector<>();
        ExecutorService executor = Executors.newFixedThreadPool(10);

        //创建服务器端的Socket
        try {
            ServerSocket server = new ServerSocket(8888);
            System.out.println("服务器已启动,等待客户端连接...");

            while(true){
                Socket socket = server.accept();
                UserThread user = new UserThread(socket, vector);
                executor.execute(user);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

/**
 * 用户线程
 */
class UserThread implements Runnable{
    private String name;
    private Socket socket;
    Vector<UserThread> vector;
    private ObjectInputStream ois;
    private ObjectOutputStream oos;
    private boolean flag=true;

    public UserThread(){

    }
    public UserThread(Socket socket,Vector<UserThread> vector){
        this.socket = socket;
        this.vector = vector;
        vector.add(this);
    }
    @Override
    public void run() {
        System.out.println("客户端已连接"+socket.getInetAddress().getHostName());
        try {
            ois = new ObjectInputStream(socket.getInputStream());
            oos = new ObjectOutputStream(socket.getOutputStream());

            while(flag){
                Message msg = (Message)ois.readObject();
                int type = msg.getType();
                switch (type){
                    case MessageType.TYPE_LOGIN:
                        name = msg.getFrom();
                        msg.setInfo("欢迎你(来自服务器)"+name);
                        oos.writeObject(msg);
                        break;

                    case MessageType.TYPE__SEND:
                        String to = msg.getTo();
                        UserThread ur;
                        int size = vector.size();
                        for (int i = 0; i < size; i++) {
                            ur = vector.get(i);
                            if(to.equals(ur.name)&& ur!=this){
                                ur.oos.writeObject(msg);
                                break;
                            }
                        }
                        break;
                }
            }
            ois.close();
            oos.close();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

用户端

package communication;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Client {
    public static void main(String[] args) {
        ExecutorService es = Executors.newSingleThreadExecutor();
        Scanner input  = new Scanner(System.in);
        try {
            Socket socket = new Socket("localhost",8888);
            System.out.println("连接服务器成功");

            //构建对象传输流
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());

            //向服务器发送登录信息
            System.out.println("请输入登录用户名:");
            String name = input.nextLine();
            Message msg = new Message(name,null,null,MessageType.TYPE_LOGIN);
            oos.writeObject(msg);
            //接收服务器消息
            msg = (Message)ois.readObject();
            System.out.println(msg.getFrom()+':'+ msg.getInfo());

            //启动读取消息的线程
            es.execute(new ReadInfoThread(ois));
            //使用主线程发送消息
            boolean flag = true;
            while (flag){
                msg = new Message();
                System.out.println("请输入要发送的用户:");
                msg.setTo(input.nextLine());
                msg.setFrom(name);
                System.out.println("INFO:");
                msg.setInfo(input.nextLine());
                msg.setType(MessageType.TYPE__SEND);
                oos.writeObject(msg);
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

//接收消息的线程
class ReadInfoThread implements Runnable{
    private boolean flag=true;
    private ObjectInputStream in;

    public ReadInfoThread(ObjectInputStream in){
        this.in = in;
    }
    public void setFlag(boolean flag) {
        this.flag = flag;
    }

    @Override
    public void run() {
        try{
            while(flag){
                Message message = (Message)in.readObject();
                System.out.println(message.getFrom()+"对我说"+message.getInfo());
            }
            if(in!=null){
                in.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

UDP协议示例

/**
*服务器端
*/
package inet;

import java.io.IOException;
import java.net.*;

public class UDPServerDemo {
    public static void main(String[] args) {
        String info = "这是一个UDP数据报";
        byte[] bytes = info.getBytes();

        try {
            DatagramPacket dp = new DatagramPacket(
                    bytes,//数据包数据
                    0,//起始位置
                    bytes.length,//读取数据长度
                    InetAddress.getByName("127.0.0.1"),//目标地址
                    8000);//目标地址端口号
            DatagramSocket server = new DatagramSocket(5000);//服务器的端口
            server.send(dp);//发送数据报
            server.close();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}


package inet;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
/**
* 客户端
*/
public class UDPClientDemo {
    public static void main(String[] args) {
        byte[] bytes = new byte[1024];
        DatagramPacket dp = new DatagramPacket(bytes,bytes.length);
        try {
            DatagramSocket socket = new DatagramSocket(8000);
            System.out.println("数据接收中...");
            socket.receive(dp);//接受数据
            String s = new String(dp.getData(),0,dp.getLength());
            System.out.println(s);
            socket.close();
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

URL

package inet;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class URLDemo {
    public static void main(String[] args) {
        try {
            URL url = new URL("http://qiniu.xiaoming.net.cn/files/2019-01-17%2015-26-01%20%E7%9A%84%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE.png");
            URLConnection urlConnection = url.openConnection();
            BufferedInputStream br = new BufferedInputStream(urlConnection.getInputStream());
            BufferedOutputStream bo = new BufferedOutputStream(new FileOutputStream("/home/xiaoming/下载/xxx.jpg"));
            byte[] bytes = new byte[1024];
            int len = -1;
            while((len = br.read(bytes))!= -1){
                bo.write(bytes,0,len);
                bo.flush();
            }
            bo.close();
            br.close();
            System.out.println("下载成功!");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}