从服务器到客户端接收数据

时间:2014-06-19 05:49:19

标签: java tcpclient tcpserver

我有这三个类,TCPClient,TCPServer和Member。我正在使用TCPClient将RequestPacket对象发送到TCPServer,TCPServer然后用字符串回复TCPClient。这是代码:

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     / * * /      包数据;

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;
    }

}

当我运行客户端时,它会将RequestPacket对象发送到TCP服务器,但由于某种原因,TCPServer不会向客户端回复rp.query值。它这样做,只有当我停止服务器时,我立即看到客户端打印的服务器响应。

如果你知道什么是错的,请帮忙。感谢。

2 个答案:

答案 0 :(得分:0)

不是将InputStream传递给BufferedReader,而是直接将其引用到DataInputStream并从那里读取UTF。

<强>样品:

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

答案 1 :(得分:0)

只需按照Jon Skeet的评论建议(将代码缩减为简短的完整的程序)并使用answer from Rod_Algonquin,我就离开了程序没有问题。添加更多代码并在每次更改后继续测试以查看程序何时中断,以便您可以找到导致问题的代码。

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; }
}

}