文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

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

2024-04-02 19:55

关注

基于TCP/IP协议的通信

通信的实现

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

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

基于UDP协议的通信

在这里插入图片描述

InetAddress




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();
   }
    }
}

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

总结

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

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯