简体   繁体   中英

Receiving data from server to client

I have these three classes, TCPClient, TCPServer and Member. I am using TCPClient to send RequestPacket object to TCPServer, which then responds back with a string to TCPClient. Here's the code:

TCPServer

import java.io.*;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.io.ObjectInputStream.GetField;
import java.net.*;

import data.RequestPacket;
public class TCPServer {
private static LinkedHashMap<Integer,String> port_database_map = new LinkedHashMap();
static{
    port_database_map.put(2131,"testing1");
    port_database_map.put(6789, "testing2");

}
public static void main(String[] args) throws Exception {
    if(args.length==1){
    String clientSentence;
    String capitalizedSentence;
    new TCPServer().sqlConnectionTest();

    ServerSocket welcomeSocket = new ServerSocket(Integer.parseInt(args[0]));

    System.out.println("Server running at "+welcomeSocket.getLocalSocketAddress()+" and port "+welcomeSocket.getLocalPort());
    Socket connectionSocket = welcomeSocket.accept();
    InputStream is = connectionSocket.getInputStream();
    ObjectInputStream ois = new ObjectInputStream(is);
    DataOutputStream outToClient;
    //DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
    while(true){

    //  BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));

        outToClient = new DataOutputStream(connectionSocket.getOutputStream());
        //clientSentence = inFromClient.readLine();
        RequestPacket rp = (RequestPacket) ois.readObject();
        outToClient.writeUTF(rp.query);
        outToClient.flush();
        System.out.println("Received object "+rp.query);
        //System.out.println("Client sentence is "+clientSentence);
        //capitalizedSentence = getClientResponse(clientSentence);
    //  outToClient.writeBytes(getClientResponse(clientSentence));


    }
    } else{
        System.out.println("Enter port numnber as argument");
        System.exit(1);
    }
}

public static String getClientResponse(String clientRequest){

    return clientRequest.toUpperCase().trim()+'\n';
}

public void sqlConnectionTest(){
    String sqlString;
    try{
        Class.forName("com.mysql.jdbc.Driver");
        System.out.println("MySQLJDBC Driver registered");
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:8889/testing1","root","root");
        if(connection!=null){
            System.out.println("You made it!");

        }else
            System.out.println("Connection failed");
    }catch(ClassNotFoundException e){
        System.out.println("Where is your mySQL JDBC Driver? "+e);

    }catch(SQLException e){
        System.out.println("Caught SQLException "+e);
    }
}
}

TCPClient

import java.io.*;
import java.net.*;
import java.util.Scanner;

import data.RequestPacket;
import data.RequestPacket.RequestType;
public class TCPClient {
public static void main(String[] args) throws UnknownHostException, IOException {
    if(args.length==1){
    String sentence;
    String modifiedSentence;

    //BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
    Socket clientSocket = new Socket("0.0.0.0",Integer.parseInt(args[0]));
    String query = "SELECT * FROM NOTHING";
    //Scanner in = new Scanner(System.in);
    DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
    RequestPacket rp = new RequestPacket(Integer.parseInt(args[0]), query, RequestType.NEW_REGISTRATION);
    OutputStream os = clientSocket.getOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(os);
    /*while(in.hasNextLine())*/if(rp.port!=0){
        DataInputStream inFromServer = new DataInputStream(clientSocket.getInputStream());
        //sentence = in.nextLine();

        //sentence = "Hello, this is Rohan";
        System.out.println("Sentence is "+rp);
        oos.writeObject(rp);
        //outToServer.writeUTF(rp+"\n");
        //outToServer.writeBytes(sentence+"\n");
        oos.flush();
        modifiedSentence = inFromServer.readLine();
        System.out.println("DONE");
        System.out.println("FROM SERVER: "+modifiedSentence);

        //outToServer.flush();
    }
    oos.close();
    os.close();
    clientSocket.close();
}else{
    System.out.println("Enter port for client to connect to");
    System.exit(1);
}
}
}

RequestPacket /* */ package data;

import java.io.Serializable;

/**
 * @author rohandalvi
 *
 */
public class RequestPacket implements Serializable {
    public int port;
    public String query;
    public RequestType type;
    public enum  RequestType{
        NEW_REGISTRATION,IN_TRANSIT_SCAN,REPLICATION,DELETE_MEMBERSHIP,REMOVE_BENEFICIARY
    }

    public RequestPacket(int port, String query,RequestType type){
        this.port = port;
        this.query = query;
        this.type = type;
    }

}

When I run client, it sends the RequestPacket object to TCP server, but for some reason, the TCPServer does not respond back with the rp.query value to the client. It does so, only when I stop the server, I immediately see the Server response printed on the client side.

Please help if you know what's wrong. Thanks.

Instead of passing the InputStream to the BufferedReader , just directly reference it to DataInputStream and read the UTF from there.

sample:

      DataInputStream inFromServer = new DataInputStream(clientSocket.getInputStream());
      modifiedSentence = inFromServer.readUTF();

Just following Jon Skeet's advice from the comments (reduce the code to a short but complete program) and using the answer from Rod_Algonquin , I'm left with a program that has no problem. Add more code and keep testing after each change to see when the program breaks so you can find what code is giving you trouble.

public class NetworkObjectString {

public static void main(String[] args) {

    Socket s = null;
    try {
        new Thread(new TcpServer()).start();
        // Wait for socket server to start
        Thread.sleep(500);
        // TcpClient
        s = new Socket(InetAddress.getLocalHost(), 54321);
        RequestPacket rp = new RequestPacket();
        rp.port = 123;
        rp.query = "dummy query";
        ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
        oos.writeObject(rp);
        oos.flush();
        System.out.println("Client send rp.query: " + rp.query);
        DataInputStream dis = new DataInputStream(s.getInputStream());
        String sq = dis.readUTF();
        System.out.println("Client received query: " + sq);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try { s.close(); } catch (Exception ignored) {}
    }
}

static class TcpServer implements Runnable {

    public void run() {

        ServerSocket ss = null;
        Socket s = null;
        try {
            s = (ss = new ServerSocket(54321)).accept();
            ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
            RequestPacket rp = (RequestPacket) ois.readObject();
            System.out.println("Server received rp: " + rp);
            String sq = rp.query + " from server";
            DataOutputStream dos = new DataOutputStream(s.getOutputStream());
            dos.writeUTF(sq);
            dos.flush();
            System.out.println("Server send query: " + sq);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try { ss.close(); } catch (Exception ignored) {}
            try { s.close(); } catch (Exception ignored) {}
        }
    }
} // TcpServer

static class RequestPacket implements Serializable {

    private static final long serialVersionUID = 1082443947105396312L;

    public String query;
    public int port;

    public String toString() { return port + " - " + query; }
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM