JAVA基于TCP和UDP的网络连接

news/2024/5/17 16:16:55 标签: java, socket, tcp, udp

tcp需要经历三次握手建立连接后发送数据">TCP:需要经历“三次握手”建立连接后,发送数据


客户端:

public class ClientSocket {
    public static void main(String[] args) throws Exception {
        Socket so = new Socket("localhost", 88);
        // 创建Socket用户,第一个参数为本地IP,第二个参数为目的端口
        System.out.println("请输入");
        BufferedReader b1 = new BufferedReader(new InputStreamReader(System.in));
        String passwd = b1.readLine();
        // 获取从控制台输入的信息
        PrintStream p = new PrintStream(so.getOutputStream());
        // 创建输出对象
        p.println(passwd);
        p.flush();
        // 输出passwd
        BufferedReader b2 = new BufferedReader(new InputStreamReader(
                so.getInputStream()));
        String r = b2.readLine();
        // 获取服务返回的数据
        System.out.println(r);
        so.close();
        // 释放资源
    }

}

服务端:

public class SocketServer {
    public static void main(String[] args) throws Exception {
        ServerSocket ss = new ServerSocket(88);
        // 创建Socket服务,注意服务的端口号
        Socket so = ss.accept();
        // 服务接收到的信息
        BufferedReader b = new BufferedReader(new InputStreamReader(
                so.getInputStream()));

        String passwd = b.readLine();
        // 读取并获取信息
        String response;
        if (passwd.equals("ZWQ")) {
            response = "有效口令";
        } else {
            response = "无效口令";
        }
        PrintStream p = new PrintStream(so.getOutputStream());
        p.println(response);
        // 返回信息
        so.close();
        ss.close();
        // 释放资源
    }

}

udp不需要建立连接直接发送">UDP:不需要建立连接,直接发送


客户端:

public class DatagramClient {
    static DatagramSocket ds;
    static byte[] buffer;
    public static void main(String[] args) throws Exception {
        ds = new DatagramSocket(8080);
        // 创建一个8080端口的DatagramSocket,注意与服务端的DatagramSocket端口号不能相同
        System.out.println("客户机正在等待服务器发送数据");
        buffer = new byte[1024];
        while (true) {
            DatagramPacket p = new DatagramPacket(buffer, buffer.length);
            ds.receive(p);
            //接收数据
            String psx = new String(p.getData(), 0, p.getLength());
            //数据类型转换
            System.out.println(psx);
            if (psx.equals("end"))
                break;
        }
        System.out.println("客户机退出运行");
    }
}

服务端:

public class DatagramServer {
    static DatagramSocket ds;
    public static void main(String[] args) throws Exception {
        byte[] buffer = new byte[1024];
        ds = new DatagramSocket(8081);
        // 创建一个8081端口的DatagramSocket,注意与客户端的DatagramSocket端口号不能相同
        BufferedReader dis = new BufferedReader(
                new InputStreamReader(System.in));
        // 从控制台输入
        System.out.println("服务器正在等待输入");
        InetAddress ia = InetAddress.getByName("localhost");
        // 获取IP
        while (true) {
            String str = dis.readLine();
            // 获取控制台输入的数据
            buffer = str.getBytes();
            ds.send(new DatagramPacket(buffer, str.length(), ia, 8080));
            // 把buffer发送给端口为8080的DatagramSocket
            if (str == null || str.equals("end")) {
                break;
            }
        }
        System.out.println("服务器退出运行");
    }

}

注意:

需要客户端和服务端都在运行状态才能测试;
TCP代码测试的时候要先运行服务端然后再运行客户端,直接运行客户端会报错,UDP可随意顺序运行;
测试过程中最常见的错误就是端口号冲突,如果发生这样的情况就重启编程工具;
切换控制台(多个程序同时运行):
这里写图片描述
点击控制台中红框中的窗口切换或者点击红框中的倒三角选择哪一个窗口


参考代码:http://download.csdn.net/detail/zhengyikuangge/9475043


http://www.niftyadmin.cn/n/897470.html

相关文章

C#识别特定的串口号

命名空间 using System.IO.Ports; //Serial using System.IO; using System.Runtime.InteropServices; //Struct using System.Management; //ManagementObjectSearchers 需要手动添加服务 private static string TWE_LITE_ID "FTDIBUS\\VID_0403PID_6001";//F…

Android布局的高按照比例来分布

线性布局&#xff08;五比一&#xff09;&#xff1a; <LinearLayoutandroid:layout_width"match_parent"android:layout_height"match_parent"android:orientation"vertical" ><LinearLayoutandroid:layout_weight"5"andro…

Centos7镜像下载及安装

http://mirrors.aliyun.com/centos/7/isos/x86_64/ CentOS-7-x86_64-DVD-2003.iso 标准安装版&#xff08;推荐&#xff09; CentOS-7-x86_64-Everything-2003.iso 完整版&#xff0c;集成所有软件&#xff08;以用来补充系统的软件或者填充本地镜像&#xff09; CentOS-7-x8…

Android适配器

目前接触到的安卓适配器主要有两种 ①&#xff1a;功能完善 例如&#xff1a;ViewPager中的PagerAdapter 具体使用请参考&#xff1a;http://blog.csdn.net/zhengyikuangge/article/details/49928691 ②&#xff1a;显示数据 例如&#xff1a;BaseAdapter,ArrayAdapter,Si…

Ubuntu和主机共享文件夹

如果在选择自动挂载后&#xff0c;不能自动mount&#xff0c;执行以下命令&#xff1a; mount -t vboxsf share /media/sf_Share

JAVA输出日历(整合代码)

①依靠算法实现&#xff1a; public static void main(String[] args) {System.out.println("欢 迎 使 用 万 年 历");Scanner input new Scanner(System.in);System.out.print("\n请选择年份&#xff1a; ");int year input.nextInt();System.out.print…

Linux--如何开启FTP服务

① 首先用命令检查是否安装了vsftpd vsftpd -version或者which vsftpd 如果没有安装 执行命令&#xff1a;sudo apt-get install vsftpd 安装完成后&#xff0c;再次输入vsftpd -version命令查看是否安装成功 ② 修改vsftpd配置文件 vi /etc/vsftpd.conf anonymous_enab…

Android四大组件之一——Broadcast Receiver

:###广播接收器&#xff1a;可以响应和监听系统事件&#xff0c;也可手动启动 ①简单手动启动代码&#xff1a; (1)MyReceiver: public class MyReceiver extends BroadcastReceiver {Overridepublic void onReceive(Context context, Intent intent) {String msg intent.ge…