通过UDP和writeUTF()发送字符串

时间:2013-10-05 15:19:37

标签: java

我有一个简单的UDP服务器和客户端。服务器使用readInDataFile()方法使用文本文件中的所有字符串填充数组列表。我的服务器可以使用"dis.readUTF(); "extracted = dis.readUTF();"轻松地从字节中读取字符串 我的客户端可以使用dis.writeUTF();

轻松编写它们

我遵循相同的结构和逻辑,将从数组中找到的字符串发送到客户端,但它没有收到任何内容。

* 我的问题:为什么客户端没有正确读取字符串?我知道服务器正在正常阅读,因为我有一个print语句来使用发送的String并进入arrayList来确定我们要打印的是什么。

我正在读取的.txt文件包含从1875年开始到2011年的字符串,因此如果客户端输入“2011”,它将传递到服务器,服务器将进入.txt文件,检索“2011动物王国John Velazquez 2:02.04”

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.Scanner;

public class DerbyUDPClient {

    public InetAddress ip = null;

    // To print the string at the end
    String finalPrint = "";
    // Socket for UDP communication with server
    DatagramSocket dgs = null;
    DatagramSocket dgs2 = null;

    // The DataGramPacket used with server
    DatagramPacket dgp = null;
    DatagramPacket dgp2 = null;

    ByteArrayOutputStream bos = null;
    DataOutputStream dos = null;

    String year = "";

    // The String to hold the user's IP Address
    String ipString = "";
    Scanner input = new Scanner(System.in);

    public DerbyUDPClient() throws IOException {
        getIPAddressServerAndYear();

    }

    public void getIPAddressServerAndYear() throws IOException {

        // Ask user for IP address, or they can just press return 
        System.out.println("Enter the IP Address of the server, please: ");
        ipString = input.nextLine();

        if (ipString.length() == 0) {

            ipString = "127.0.0.1";
        }

        try {
            ip = InetAddress.getByName(ipString);
        } catch (UnknownHostException e) {

            e.printStackTrace();
        }

        // Ask user for IP address, or they can just press return 
        System.out.println("Please enter a year between 1875 and 2011: ");

        year = input.nextLine();

        // Checks to see if the user has inputed a year 
        if (isInteger(year) == true) {

            // write and then receive

            dgs = new DatagramSocket();

            bos = new ByteArrayOutputStream();

            dos = new DataOutputStream(bos);

            dos.writeUTF(year);


            dgp = new DatagramPacket(bos.toByteArray(), bos.size());

            dgp.setAddress(InetAddress.getLocalHost());
            dgp.setPort(28150);

            dgs.send(dgp);

            // receive


            dgs.receive(dgp);

            ByteArrayInputStream bis = new ByteArrayInputStream(dgp.getData());

            DataInputStream dis = new DataInputStream(bis);
            finalPrint = dis.readUTF();
            System.out.println(finalPrint);

            dgs.close();
        }

    }

    public boolean isInteger(String input) {
        try {
            Integer.parseInt(input);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static void main(String[] args) throws IOException {

        new DerbyUDPClient();

    } // end main

} // end DerbyUDPClient


<><><><><><><><><><><><><><><><><><><><><><>><>><><><><>><><><> New class below
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;

public class DerbyUDPServer {

    // Socket for UDP communication with clients
    DatagramSocket dgs = null;
    DatagramSocket dgs2 = null;

    // The DataGramPacket used
    DatagramPacket dgp = null;

    ByteArrayInputStream bis = null;

    DataInputStream dis = new DataInputStream(bis);

    int clientPort = 0;

    DatagramPacket dgp2 = null;

    // The string converted to an int is held in this variable
    int parsedString = 0;

    // Flag set to false when server should close
    boolean listening = true;

    // The String that is used to hold the extracted String
    String extracted = "";

    // Total number of clients server has sent data to
    int clientCount = 0;

    // Port number that server listens on
    static final int SERVER_PORT = 31250;

    ByteArrayOutputStream bos = null;
    DataOutputStream dos = null;

    // Array list containing a list of strings describing
    // Kentucky derby winners
    ArrayList<String> winners = new ArrayList<String>();

    public DerbyUDPServer() throws IOException {

        readInDataFile();
        handleClients();

    } // end DerbyUDPServer constructor

    protected void readInDataFile() throws IOException {
        int winIdx = 0;
        String singleWinner;

        BufferedReader in = new BufferedReader(new FileReader("derby.txt"));

        while ((singleWinner = in.readLine()) != null) {

            winners.add(singleWinner);
            winIdx++;
        }

        in.close();

    } // end readInDataFile

    /*
     * Displays IP address and port number that clients can use to contact the
     * server to the console.
     */
    protected void displayContactInfo() {
        try {
            // Display contact information.
            System.out.println("Number Server standing by to accept Clients:"
                    + "\nIP : " + InetAddress.getLocalHost() + "\nPort: "
                    + dgs.getLocalPort() + "\n\n");

        } catch (UnknownHostException e) {
            // NS lookup for host IP failed?
            // This should only happen if the host machine does
            // not have an IP address.
            e.printStackTrace();
        }

    } // end displayContactInfo

    public void handleClients() throws IOException {

        try {

            dgs = new DatagramSocket(28150);

            dgp = new DatagramPacket(new byte[50], 50);

        } catch (SocketException e) {

            e.printStackTrace();

        }

        displayContactInfo();

        // Receive and then write

        // receive here

        dgs.receive(dgp);

        // Prints out the IP address and Port of the DataGramPacket 
        System.out.println(dgp.getAddress());
        System.out.println(dgp.getPort());

        // Extract the string from the bytes 

        ByteArrayInputStream bis = new ByteArrayInputStream(dgp.getData());

        DataInputStream dis = new DataInputStream(bis);
        // Read in the string from the DataInputString...
        try {
            extracted = dis.readUTF();
        } catch (IOException e) {

            e.printStackTrace();
        }

        // System.out.println("You entered the year: " + extracted);
        // Converts the String to an integer 
        parsedString = Integer.parseInt(extracted);

        // This below prints, so I am obviously receiving the integer year from the client

         System.out.println(getYearLine(parsedString));

        // Write below

        bos = new ByteArrayOutputStream();

        dos = new DataOutputStream(bos);

        dos.writeUTF(getYearLine(parsedString));

        dgp2 = new DatagramPacket(bos.toByteArray(), bos.size());

        dgp2.setAddress(dgp.getAddress());
        dgp2.setPort(dgp.getPort());

        dgs.send(dgp2);

        while(listening == true){
            handleClients();
        }

    }

    public String getYearLine(int year) {

        if (year < 2012 && year > 1874) {

            return winners.get(2011 - year);

        } else {

            return "no derby info for that year";
        }

    } // getYearLine

    public static void main(String[] args) throws IOException {

        new DerbyUDPServer();

    } // end main

} // end DerbyUDPServer

0 个答案:

没有答案