java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > java网络编程

一篇文章带你入门java网络编程

作者:正函数-

网络编程是指编写运行在多个设备(计算机)的程序,这些设备都通过网络连接起来。本文介绍了一些网络编程基础的概念,并用Java来实现TCP和UDP的Socket的编程,来让读者更好的了解其原理

基于TCP/IP协议的通信

通信的实现

ServerSocket用来监听来自客户端的连接,当没有连接时,它处于阻塞状态

客户端使用Socket连接到指定的服务器

基于UDP协议的通信

在这里插入图片描述

InetAddress

/**
 *
 * InetAddressDemo
 *
 *
 */

public class InetAddressDemo {

    public static void main(String[] args) throws IOException {
        InetAddress baidu = InetAddress.getByName("www.baidu.com");
        System.out.println(baidu);
        System.out.println(baidu.getHostAddress());//获取主机地址
        System.out.println(baidu.isReachable(1000));//是否可达
        System.out.println("====================================================================================");
        InetAddress local = InetAddress.getByAddress(new byte[]{127, 0, 0, 1});
        System.out.println(local.getHostName());//获取主机名
        System.out.println(local.isReachable(1000));//是否可达
    }
}

在这里插入图片描述

案例演示 (简易聊天室)

package javaserver.TcpServer;
import JAVAClient.TcpClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class tcpServer {
    public static ExecutorService threadPool= Executors.newFixedThreadPool(10);
    public static List<Socket> socketList= Collections.synchronizedList(new ArrayList<>());
    public static void main(String[] args) {
//
//        try {
//
//            //接受客户端的请求
//            ServerSocket serverSocket=new ServerSocket(9000);
//            while (true){
//                Socket socket = serverSocket.accept();//封装了一些客户端的信息
//                System.out.println("请求;" + socket.toString());
//
//                PrintStream ps=new PrintStream(socket.getOutputStream());
//                ps.println("welcome "+ socket.getInetAddress().getHostAddress());
//                socket.close();
//            }
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
        try {
            ServerSocket serverSocket = new ServerSocket(9000);
            while (true){
                Socket socket = serverSocket.accept();
                socketList.add(socket);
                threadPool.submit(new ThreadTask(socket));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
class  ThreadTask implements  Runnable{
    private Socket  socket;
    private BufferedReader reader;
    public ThreadTask(Socket socket) {
        this.socket = socket;
        try {
            this.reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void run() {
        try {
            String line;
            while ((line=reader.readLine())!=null){
                for (Socket client: tcpServer.socketList){
                    String from=socket.getInetAddress().getHostAddress()+":::"+socket.getPort();
                    String content= from+"说"+line;
                    new PrintStream(client.getOutputStream()).println(content);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
package JAVAClient;
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TcpClient {
    public static ExecutorService threadPool= Executors.newFixedThreadPool(3);
    public static void main(String[] args) throws IOException {
//        Socket socket=new Socket("127.0.0.1",9000);
//        BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
//        String s = br.readLine();
//        System.out.println(s);
        Socket socket=new Socket("127.0.0.1",9000);
        threadPool.submit(new ReadTask(socket));
        threadPool.submit(new WriteTask(socket));


    }
}

class ReadTask implements Runnable{
   private Socket socket;
   private BufferedReader reader;
    public ReadTask(Socket socket) {
        this.socket = socket;
        try {
            this.reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void run() {
        try {
            String line;
            while ((line=reader.readLine())!=null){
                System.out.println(line);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class WriteTask implements Runnable{
    private Socket socket;
    private PrintStream writer;
    public WriteTask(Socket socket) {
        this.socket = socket;
        try {
            writer=new PrintStream(socket.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void run() {
        Scanner scanner = new Scanner(System.in);
        String line;
        while ((line=scanner.nextLine())!=null){
            writer.println(line);
        }
    }
}

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

UDP 演示

服务端

package javaserver.TcpServer;
import java.net.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class UdpServer {

    public static ExecutorService threadPool= Executors.newFixedThreadPool(10);
    public static List<InetSocketAddress> addressesList=new ArrayList<>();

    public static void main(String[] args) {
        try {
            DatagramSocket socket=new DatagramSocket(9001);
            // 随时通知
            threadPool.submit(new SendTask(socket));
            //接受访问 并且记录
            byte[] buffer=new byte[1024];
            DatagramPacket packet=new DatagramPacket(buffer,buffer.length);
            while (true){
                socket.receive(packet);
                addressesList.add((InetSocketAddress) packet.getSocketAddress());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class SendTask implements Runnable{
    private DatagramSocket socket;
    public SendTask(DatagramSocket socket) {
        this.socket = socket;
    }
    @Override
    public void run() {
        try {
            Scanner scanner = new Scanner(System.in);
            String line;
            while ((line= scanner.nextLine())!=null){
                for (InetSocketAddress isa:UdpServer.addressesList){
                    byte[] buffer=line.getBytes();
                    DatagramPacket packet=new DatagramPacket(buffer,buffer.length,isa.getAddress(),isa.getPort());
                    socket.send(packet);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

客户端

package JAVAClient;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class UdpClient {
    public static ExecutorService threadPool= Executors.newFixedThreadPool(3);
    public static void main(String[] args) {
        try {
            DatagramSocket socket=new DatagramSocket();
//            注册
             DatagramPacket packet=new DatagramPacket(new byte[]{1},1, InetAddress.getByName("127.0.0.1"),9001);
             socket.send(packet);
//             接收
            threadPool.submit(new ReceiveTask(socket));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
class ReceiveTask implements Runnable{
    private DatagramSocket socket;
    public ReceiveTask(DatagramSocket socket) {
        this.socket = socket;
    }
    @Override
    public void run() {
   try {
       byte[] buffer=new  byte[1024];
       DatagramPacket packet=new DatagramPacket(buffer,buffer.length);
       while (true){
           socket.receive(packet);
           String line =new String(packet.getData(),0, packet.getLength());
           System.out.println(line);
       }
   } catch (Exception e) {
       e.printStackTrace();
   }
    }
}

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

总结

本篇文章就到这里了,希望能给你带来帮助,也希望您能够多多关注脚本之家的更多内容!

您可能感兴趣的文章:
阅读全文