客户端服务器udp套接字 [英] client server udp socket

查看:115
本文介绍了客户端服务器udp套接字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨我有一个无法运行的udp客户端服务器代码我问一般问题Shane是个好孩子两个代码都没有出现错误但是当我运行代码时它输出
DatagramPacket sendPacket =
new DatagramPacket(sendData,sendData.length,IPAddress,9876);
而不是让客户端问候服务器。流程应该是服务器初始化并等待客户端 - 客户端问候服务器 - 服务器询问问题 - 客户端响应问题 - 服务器符合是否投票并显示天气或不是人像=。
任何关于如何舍入代码的建议都会受到欢迎
听到的是服务器代码

Hi i have a udp client server code that is not working i ask a general question "Is shane a good kid"both codes have no errors that come up but when i run the code it outputs DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876); instead of letting the client greet the server. The flow should be Server initializes and waits for client--client greets server -- server asks the question -- client responds to question-- server tallies the yes no votes and displays weather or not the person is like =. any advice on how to round the code out would be welcomed hear is the server code

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

这里是客户端代码
import java.io. ;
import 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在服务器端运行代码...有代码本身的一些问题。第一个是您尝试保留客户端连接实例的Array的索引。此时,你只有一个......

I get a NullPointException running your code in the Server-side... There are a few problems in the code itself. The first one is the index of the Array that you attempt to keep the instance of the Clients connection. At this point, you have only one...

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 ...

However, at this point, your code is prone to NullPointException as you try to iterate over it 5 times...

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... 

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

Here's the result of running the code...

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)

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

Looking at this exception, I noticed that since your buffer would not be null, your address is the problem, since you create a new DatagramPacket without both the IP and the Port number of the client connection... You have to pass them to the DatagramPacket instance so that the server knows who is the client trying to communicate... A very simple/basic example of what you are trying to achieve is at http://systembash.com/content/a-simple-java-udp-server-and-udp-client/. Below is my initial fixing of the code... Your answers will still need some work on the buffer, which I will leave it as an exercise...

这是一个服务器的固定代码只接受1个客户端...我会留下多线程的东西+数据处理程序作为练习......

Here's a fixed code for Server that accepts only 1 client... I will leave the Multi-threaded stuff + the data handler for you as an exercise...

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上打开的套接字。然后,您可以使用客户端连接到服务器。

You MUST execute the server first, as it will listen to the socket open on port 9876. Then, you can connect to the server with the client.

###### 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执行一个新的Runnable http://java-x.blogspot.com/2006/11/java-5-executors-threadpool.html )。考虑如上所述创建一个Runnable实例,并将服务器的代码放在public void run(){}方法实现中......我将把这个作为练习留给你...

As it seems that your requirement is to design a Server that can handle multiple clients and count on the number of votes, I would also recommend you to use a Multi-threaded version of the server by using different Threads to deal with each client in its own thread and update the value of the static counter (an example is a while(true) loop executing a new Runnable with an Executor here http://java-x.blogspot.com/2006/11/java-5-executors-threadpool.html). Think about creating a Runnable instance as described, and placing the server's code in the public void run() {} method implementation... I will leave this as an exercise for you as well...

这篇关于客户端服务器udp套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆