客户端服务器udp套接字

2024-01-06

您好,我有一个 udp 客户端服务器代码无法正常工作,我问一个一般性问题“Shane 是个好孩子吗”这两个代码都没有出现错误,但是当我运行它输出的代码时 数据报发送数据包 = 新的 DatagramPacket(sendData, sendData.length, IPAddress, 9876); 而不是让客户端向服务器打招呼。流程应该是服务器初始化并等待客户端--客户端向服务器打招呼--服务器提问--客户端回答问题--服务器统计是否票并显示天气或某人是否喜欢=。 任何有关如何舍入代码的建议将受到欢迎 听到的是服务器代码

import java.net.*;

public class VotingServer {
//private static final int yes = 0;
private static int yes2;

public static void main(String[] args, int getrep) throws Exception{
    // part 1: initialization
    DatagramSocket serverSocket = new DatagramSocket(9876);
    byte[] receiveData = new byte[1024];
    byte[] sendData = new byte[1024];
    InetAddress[] IPAddressList = new InetAddress[5];
    int[] portList = new int[5];

    // part 2: receive the greeting from clients
    for (int i=0; i<1; i++) {
        DatagramPacket receivePacket = 
            new DatagramPacket(receiveData, receiveData.length);
        serverSocket.receive(receivePacket);
        String greeting = new String(receivePacket.getData());
        System.out.println("From Client: " + greeting);

        IPAddressList[i] = receivePacket.getAddress();
        portList[i] = receivePacket.getPort();
    } // for (i)

    // part 3: broadcast the votiong question to all clients
    String question = "is shane a good kid 1 for yes 0 no?\n";
    for (int i=0; i<5; i++) { 
        sendData = question.getBytes();
        DatagramPacket sendPacket = 
            new DatagramPacket(sendData, sendData.length);
        serverSocket.send(sendPacket);

    // part 5: receive the age of client (B)
        DatagramPacket receivePacket = 
            new DatagramPacket(receiveData, receiveData.length);
        serverSocket.receive(receivePacket);
        String ageStr = new String(receivePacket.getData());
        yes2 = Integer.parseInt(ageStr);

        IPAddressList[i] = receivePacket.getAddress();
        portList[i] = receivePacket.getPort();

    // part 6: compute the price (C)
    double count= 0; 
    double no = 0;

    if (yes2 >= 1 ) count = 1;
    else 
        if (yes2 <= 0 ) no = 1;

    // part 7: send the price to client
    String rep = null;
    String countStr = ""+count+"\n";
    String noStr = ""+no+"\n";
    if (no < count) rep = "Is a good kid";
    else 
        if (no > count) rep = "is a bad kid";
    System.out.println(" "+getrep);
    sendData = countStr.getBytes();
    sendData = noStr.getBytes();
    sendData = rep.getBytes();
    DatagramPacket sendPacket1 = 
        new DatagramPacket(sendData, sendData.length);
    serverSocket.send(sendPacket1);

} // main()

}} // UDPServer

这是客户端代码 导入java.io。; 导入java.net.;

public class ClientVoting {

    public static void main(String[] args) throws Exception {
        // part 1: initialization
        BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
        DatagramSocket clientSocket = new DatagramSocket();
        InetAddress IPAddress = InetAddress.getByName("localhost");
        byte[] sendData = new byte[1024];
        byte[] receiveData = new byte[1024];



        String sentence = inFromUser.readLine();
        sendData = sentence.getBytes();
        DatagramPacket sendPacket = 
            new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
        clientSocket.send(sendPacket);


        // part 2: receive the question from server
        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
        clientSocket.receive(receivePacket);
        String question = new String(receivePacket.getData());
        System.out.println("From Server:" + question);

        String yes2 = inFromUser.readLine();
        sendData = yes2.getBytes();
        DatagramPacket sendPacket1 = 
            new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
        clientSocket.send(sendPacket1);


        // part 4: get the price from server
        receivePacket = new DatagramPacket(receiveData, receiveData.length);
        clientSocket.receive(receivePacket);
        String rep = new String(receivePacket.getData());
        System.out.println("the answer is " + rep);

        // part 4: close the socket
        clientSocket.close();

    } // main()

    } // class UDPClient

谢谢 SPF


我在服务器端运行您的代码时遇到 NullPointException...代码本身存在一些问题。第一个是您尝试保留客户端连接实例的数组的索引。此时,你只有一...

for (int i=0; i<1; i++) {
    DatagramPacket receivePacket = 
        new DatagramPacket(receiveData, receiveData.length);
    serverSocket.receive(receivePacket);
    String greeting = new String(receivePacket.getData());
    System.out.println("From Client: " + greeting);

    IPAddressList[i] = receivePacket.getAddress();
    portList[i] = receivePacket.getPort();
} // for (i)

然而,此时,当您尝试迭代 5 次时,您的代码很容易出现 NullPointException...

String question = "is shane a good kid 1 for yes 0 no?\n";
for (int i=0; i<5; i++) { 
    sendData = question.getBytes();
    DatagramPacket sendPacket = 
        new DatagramPacket(sendData, sendData.length);
    serverSocket.send(sendPacket);   <<<<---- NPE prone code line... 

这是运行代码的结果...

From Client: hello
Exception in thread "main" java.lang.NullPointerException: null buffer || null address
    at java.net.PlainDatagramSocketImpl.send(Native Method)
    at java.net.DatagramSocket.send(DatagramSocket.java:629)
    at com.vasoftware.sf.common.VotingServer.main(VotingServer.java:38)

看看这个异常,我注意到,由于您的缓冲区不会为空,所以您的地址就是问题,因为您创建了一个新的 DatagramPacket,而没有客户端连接的 IP 和端口号...您必须将它们传递给DatagramPacket 实例,以便服务器知道谁是尝试通信的客户端...您想要实现的一个非常简单/基本的示例位于http://systembash.com/content/a-simple-java-udp-server-and-udp-client/ http://systembash.com/content/a-simple-java-udp-server-and-udp-client/。下面是我对代码的初步修复...您的答案仍然需要在缓冲区上进行一些工作,我将把它作为练习...

这是仅接受 1 个客户端的服务器的固定代码...我将把多线程内容 + 数据处理程序留给您作为练习...

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Arrays;

public class VotingServer {

  //private static final int yes = 0;
    private static int yes2;

    public static void main(String[] args) throws Exception {
        // part 1: initialization
        DatagramSocket serverSocket = new DatagramSocket(9876);
        byte[] receiveData = new byte[1024];
        byte[] sendData = new byte[1024];
        InetAddress IPAddressList;
        int portList = -1;

        // part 2: receive the greeting from clients
        System.out.println("Ready to receive connections at port " + serverSocket.getLocalPort());
        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
        serverSocket.receive(receivePacket);
        String greeting = new String(receivePacket.getData());
        System.out.println("From Client: " + greeting);

        IPAddressList = receivePacket.getAddress();
        portList= receivePacket.getPort();

        // part 3: broadcast the votiong question to all clients
        String question = "is shane a good kid 1 for yes 0 no?\n";
        sendData = question.getBytes();
        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddressList, portList);
        serverSocket.send(sendPacket);

    // part 5: receive the age of client (B)
        receiveData = new byte[1024];
        receivePacket = new DatagramPacket(receiveData, receiveData.length);
        serverSocket.receive(receivePacket);
        String ageStr = new String(receivePacket.getData());

        try {
            yes2 = Integer.parseInt(ageStr);   //<<<----- WILL NEVER GET THE VALUE... LEAVING IT AS AN EXERCISE....

        } catch (NumberFormatException nfe) {
            yes2 = 0;
        }

        receivePacket.getAddress();
        receivePacket.getPort();

        // part 6: compute the price (C)
        double count= 0; 
        double no = 0;

        if (yes2 >= 1 ) count = 1;
        else 
            if (yes2 <= 0 ) no = 1;

        // part 7: send the price to client
        // ALSO FIXING SOME CODE HERE AS WELL....
        String rep = null;
        rep = no < count ? "Is a good kid" : "is a bad kid";
        rep += " Server Count: " + count;

        sendData = rep.getBytes();
        DatagramPacket sendPacket1 = new DatagramPacket(sendData, sendData.length, IPAddressList, portList);
        serverSocket.send(sendPacket1);
    }
}

这是客户端:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class ClientVoting {

    public static void main(String[] args) throws Exception {
        // part 1: initialization
        BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
        DatagramSocket clientSocket = new DatagramSocket();
        InetAddress IPAddress = InetAddress.getByName("localhost");
        byte[] sendData = new byte[1024];
        byte[] receiveData = new byte[1024];

        System.out.print("What's the question? ");
        String sentence = inFromUser.readLine();
        sendData = sentence.getBytes();
        System.out.println("Attempting to connect the server at port " + 9876);
        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
        clientSocket.send(sendPacket);

        System.out.println("Initial greeting sent... Waiting for response...");

        // part 2: receive the question from server
        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
        clientSocket.receive(receivePacket);
        String question = new String(receivePacket.getData());
        System.out.println("From Server:" + question);

        String yes2 = inFromUser.readLine();
        sendData = yes2.getBytes();
        DatagramPacket sendPacket1 = 
            new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
        clientSocket.send(sendPacket1);


        // part 4: get the price from server
        receiveData = new byte[1024];
        receivePacket = new DatagramPacket(receiveData, receiveData.length);
        clientSocket.receive(receivePacket);
        String rep = new String(receivePacket.getData());
        System.out.println("the answer is " + rep);

        // part 4: close the socket
        clientSocket.close();

    } // main()
}

您必须首先执行服务器,因为它将侦听端口 9876 上打开的套接字。然后,您可以使用客户端连接到服务器。

###### Here's the output in the server-side... Just added a few details of what's going on...
Ready to receive connections at port 9876
From Client: Marcello

####### Here's the output of the client:
What's the question? Marcello
Attempting to connect the server at port 9876
Initial greeting sent... Waiting for response...
From Server:is shane a good kid 1 for yes 0 no?
the answer is is a bad kid Server Count: 0.0

由于您的要求似乎是设计一个可以处理多个客户端并计算投票数的服务器,我还建议您使用服务器的多线程版本,通过使用不同的线程来处理其中的每个客户端自己的线程并更新静态计数器的值(示例是 while(true) 循环使用 Executor 执行新的 Runnablehttp://java-x.blogspot.com/2006/11/java-5-executors-threadpool.html http://java-x.blogspot.com/2006/11/java-5-executors-threadpool.html)。考虑按照描述创建一个 Runnable 实例,并将服务器的代码放置在 public void run() {} 方法实现中...我也将把它作为练习留给您...

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

客户端服务器udp套接字 的相关文章

随机推荐

  • mysql n:m 关系:查找具有多个特定关系的行

    我有两个 SQL 表 产品 和 标签 它们具有 n m 关系 使用第三个表 product tags 我想使用查询来查找具有多个特定标签的每个产品 例如 查找与标签 1 23 和 54 相关的所有产品 有没有办法只用一个查询来做到这一点 您
  • 将驱动程序对象的单个实例传递给所有其他类(Testng 框架)

    我有一个在类示例中初始化的驱动程序对象 我也想将驱动程序对象传递给其他类 但我得到一个空指针异常 我的代码是 样本类 public class sample WebDriver driver Test priority 1 public v
  • 用于 POST 请求的 Django Rest 框架自定义过滤器

    在filters py中 我有一个CustomFilter定义了具有类型值的ComboSortFilter and IntegerListFilter 在views py中 我定义了一个ViewSet 它具有filter class Cus
  • 我可以使用在启动期间配置的 MvcJsonOptions 在自定义中间件中进行序列化吗?

    我正在构建一个带有用于全局异常处理的中间件的 ASP NET Core Api 在Startup类中 我配置了一些用于所有控制器的 JSON 选项 public void ConfigureServices IServiceCollecti
  • TensorFlow 的内存泄漏

    我的 TensorFlow 出现内存泄漏 我提到了Tensorflow 即使关闭会话也会发生内存泄漏 https stackoverflow com questions 35695183 tensorflow memory leak eve
  • Vue.js filterBy 在多个字段中搜索

    如何通过在多个搜索键中搜索来进行过滤 我正在尝试这样的事情 但是 当然 它不会起作用 tr AFAIK 没有记录 filterBy 自定义过滤器 但您可以使用method制作你自己的过滤器 var demo new Vue el demo
  • 只能使用绝对 URI 作为基地址

    请帮助获得例外using ServiceHost host new ServiceHost typeof HelloService HelloService 在下面的代码中 例外 只有绝对 URI 可以用作基地址 WCF 主机应用程序 cl
  • Redis 尝试连接到 Heroku 上的本地主机而不是 REDIS_URL

    我有一个 Rails 应用程序 它使用 Redis 进行后台作业 在 Heroku 上 我使用 Heroku Redis 插件 当我部署到 Heroku 时 出现以下错误 Redis CannotConnectError Error con
  • 为什么Android开发中一定要把这个Context作为参数传递呢?

    这是来自developer android com 上的课程 public void sendMessage View view Intent intent new Intent this DisplayMessageActivity cl
  • 打印对象如何会导致与 str() 和 repr() 不同的输出?

    我正在解释器上测试一些代码 我注意到一些意外的行为sqlite3 Row http docs python org library sqlite3 html sqlite3 Row class 我的理解是print obj总是会得到相同的结
  • django-compressor 离线生成错误

    我正在尝试使用 django compressor 压缩我的 CSS 文件 但我不断收到此错误 compressor exceptions OfflineGenerationError You have offline compressio
  • 如何在 React Navigation 中刷新

    一旦我删除用户令牌 用户就会重定向到登录页面 但是如果我用其他用户登录 主页仍然显示以前的用户信息 这是因为我没有刷新主页 如何在反应导航中手动重新初始化 主页 MainPage Logged in as matt gt Logout gt
  • 从后台工作人员更新 GUI

    问题的名称是 从后台工作人员更新 GUI 但正确的名字是 world 从后台工作人员更新 GUI 或从后台工作人员报告多个变量 整数除外 请让我解释一下我的情况 在一个程序中 我有一个后台工作人员来分析信息 分析的结果是 表单 GUI 元素
  • 像 root 用户一样运行 PHP shell_exec()

    我构建了一个 PHP 应用程序 在其中为 Linux debian Jessie 创建命令行功能 一切正常 但我需要能够使用一些命令 例如 root 用户 有没有办法使用 shell exec 或类似的命令通过 PHP 像 root 用户一
  • postgres 中的顺序扫描和位图堆扫描有什么区别?

    在解释命令的输出中 我发现了两个术语 顺序扫描 和 位图堆扫描 有人可以告诉我这两种扫描有什么区别吗 我使用的是PostgreSql http www postgresql org docs 8 2 static using explain
  • Node.js 和express.js 中基于组/规则的授权方法

    Express js 中基于角色的授权有哪些好的策略 特别是对于快递资源 With 快递资源 https github com visionmedia express resource没有处理程序 所以我认为有三种选择 使用中间件 将授权函
  • 服务器管理 - 需要脚本来监控服务器上的可用空间

    需要脚本来监控服务器上的可用空间如果可用内存空间达到某个阈值发送警报邮件 PS 我认为解决方案是 Power Shell Windows Timer Job 不过我对 Power Shell 还很陌生 您可以使用如下命令获取可用磁盘空间 w
  • PHP 中的日历日视图

    我正在努力向现有日历解决方案添加日视图选项 像许多实现自己的日历的人一样 我正在尝试对 Google 日历进行建模 他们有一个出色的日历解决方案 并且他们的日视图提供了很大的灵活性 大多数情况下 实施进展顺利 然而 当涉及到冲突事件时 我遇
  • 如何更改DataGridView中某些单元格的边框颜色?

    我需要编程更改 CellFormatting 事件中某些单元格的边框颜色 单个单元的板颜色可以更改吗 你可以画一个矩形 在此示例中 我在选定的单元格上放置了红色边框 private void dataGridView CellPaintin
  • 客户端服务器udp套接字

    您好 我有一个 udp 客户端服务器代码无法正常工作 我问一个一般性问题 Shane 是个好孩子吗 这两个代码都没有出现错误 但是当我运行它输出的代码时 数据报发送数据包 新的 DatagramPacket sendData sendDat