简体   繁体   中英

Client - Server connection/communication (java sockets)

I am trying to make an application (client) for Android that collects coordinates from GPS, it calculates the speed that the user is moving and then it sends them to another application for Android (server). At server i check if the user is runing too fast and i send a message (from server to client) to slow down and i also check if two users are going to possibly crash and i am sending an appropriate message.

My problem is that when both applications seem to work fine (client is running and showing speed, server is running and showing the port that is listening and its ip), server doesn't receive the data i am sending from client. I can't understand what is wrong. And i am not sure if server is not receiving or client is not sending.

My server code is this:

private static Socket socket;
TextView msg;
private ArrayList<String[]> client = new ArrayList<String[]>();


protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    msg=(TextView)findViewById(R.id.msg);
    try
    {

        int port = 8080;
        ServerSocket serverSocket = new ServerSocket(port);
        msg.setText("Server Started and listening to the port 8080"+" "+getIpAddress());
        //Server is running always. This is done using this while(true) loop
        while(true)
        {
            //Reading the message from the client
            socket = serverSocket.accept();
            InputStream is = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String elements = br.readLine();
            String[] parts = elements.split("_");
            String part1 = parts[0]; // x1
            String part2 = parts[1]; // y1
            String part3 = parts[2]; // speed
            String part4 = parts[3]; // direction 1
            String part5 = parts[4]; // direction 2
            String part6 = parts[5]; // x2
            String part7 = parts[6]; // y2
            parts[7] = Integer.toString(socket.getPort()); // client's port
            msg.setText("Message received from client is "+elements);

            if(client.contains(parts[7])) {
                client.remove(client.indexOf(parts[7]));
                client.add(parts);
            }
            else {
                client.add(parts);
            }

            String returnMessage;

            if (Integer.parseInt(parts[2])>130) {

                try {
                    returnMessage = "Slow down, you are not the Flash!";
                } catch (NumberFormatException e) {
                    returnMessage = e.toString();
                }

                //Sending the response back to the client.
                OutputStream os = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(os);
                BufferedWriter bw = new BufferedWriter(osw);
                bw.write(returnMessage);
                msg.setText("Message sent to the client is " + returnMessage);
                bw.flush();
            }
            double x,y;
            int distance;

            if (Integer.parseInt(parts[2])>50){
                for (int i=0; i<client.size(); i++){
                    String[] temp= new String[6];
                    temp=client.get(i);
                    distance= findDistance(Double.parseDouble(parts[0]), Double.parseDouble(parts[1]),Double.parseDouble(temp[0]), Double.parseDouble(temp[1]));
                    if (distance<500 && distance!=0){
                        if (Integer.parseInt(temp[2])>50){

                            //Βρίσκουμε τις συντεταγμένες του θεωρητικού σημείου πρόσκρουσης
                            x=findXIntersectionPoint(Double.parseDouble(parts[0]), Double.parseDouble(parts[1]),Double.parseDouble(temp[0]), Double.parseDouble(temp[1]),Double.parseDouble(parts[5]), Double.parseDouble(parts[6]),Double.parseDouble(temp[5]), Double.parseDouble(temp[6]));
                            y=findYIntersectionPoint(Double.parseDouble(parts[0]), Double.parseDouble(parts[1]), Double.parseDouble(parts[5]), Double.parseDouble(parts[6]),x);

                            //Βρίσκουμε αν η κατεύθυνση του κάθε οχήματος είναι προς το σημείο πρόσκρουσης
                            if ((findLongitude(Double.parseDouble(parts[0]),Double.parseDouble(parts[5])).equals(parts[3])) && (findLatitude(Double.parseDouble(parts[1]), Double.parseDouble(parts[6])).equals(parts[4])) && (findLongitude(Double.parseDouble(temp[0]),Double.parseDouble(temp[5])).equals(temp[3])) && (findLatitude(Double.parseDouble(temp[1]), Double.parseDouble(temp[6])).equals(temp[4]))){

                                int dist1, dist2;
                                float t1,t2;

                                dist1= findDistance(Double.parseDouble(parts[0]), Double.parseDouble(parts[1]), x,y);
                                dist2= findDistance(Double.parseDouble(temp[0]), Double.parseDouble(temp[1]), x,y);

                                t1= dist1/Float.parseFloat(parts[2]);
                                t2= dist2/Float.parseFloat(temp[2]);

                                if (t1-t2>-2 && t1-t2<2){

                                    try {
                                        returnMessage = "Possible Collision Slow Down!";
                                    } catch (NumberFormatException e) {
                                        returnMessage = e.toString();
                                    }

                                    OutputStream os = socket.getOutputStream();
                                    OutputStreamWriter osw = new OutputStreamWriter(os);
                                    BufferedWriter bw = new BufferedWriter(osw);
                                    bw.write(returnMessage);
                                    msg.setText("Message sent to the client is " + returnMessage);
                                    bw.flush();

                                }
                            }

                        }
                    }
                }
            }
            }
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    finally
    {
        try
        {
            socket.close();
        }
        catch(Exception e){}
    }
}
private int findDistance(final double a1, final double b1, final double a2, final double b2) {

            double x1=a1;
            double y1=b1;
            double x2=a2;
            double y2=b2;
            int distance;

            // Convert degrees to radians
            x1=x1*Math.PI/180.0;
            y1=y1*Math.PI/180.0;
            x2=x2*Math.PI/180.0;
            y2=y2*Math.PI/180.0;
            // radius of earth in metres
            double r = 6378100;
            // P
            double rho1 = r * Math.cos(y1);
            double z1 = r * Math.sin(y1);
            double k1 = rho1 * Math.cos(x1);
            double l1 = rho1 * Math.sin(x1);

            // Q
            double rho2 = r * Math.cos(y2);
            double z2 = r * Math.sin(y2);
            double k2 = rho2 * Math.cos(x2);
            double l2 = rho2 * Math.sin(x2);

            // Dot product
            double dot = (k1 * k2 + l1 * l2 + z1 * z2);
            double cos_theta = dot / (r * r);

            double theta = Math.acos(cos_theta);
            // Distance in Metres
            theta = (r*theta);
            distance = (int)theta;

    return distance;
}

public double findXIntersectionPoint(double x1, double y1, double x3, double y3, double x2, double y2, double x4, double y4)
{
    double z1=x1, z2=x2, z3=x3, z4=x4;
    double w1=y1, w2=y2, w3=y3, w4=y4;
    double x, ya, yb, lamda1, lamda2;

    lamda1=(w2-w1)/(z2-z1);
    lamda2=(w4-w3)/(z4-z3);

    x=(lamda1*z1-lamda2*z3-w1+w3)/(lamda1-lamda2);  //Λύση του συστήματος των 2 ευθειών ως προς x

    return x;
}

public double findYIntersectionPoint (double x1, double y1,double x2, double y2, double x)
{
    double y, lamda;
    double z=x, z1=x1, z2=x2;
    double w1=y1, w2=y2;

    lamda= (w2-w1)/(z2-z1);
    y= lamda*(z-z1)+w1;

    return y;
}

private String findLongitude(double x1, double x2) {

            double z1=x1, z2=x2;
            String dir1;
            // Using the longitudes
            if(z2>z1)
            {
                dir1="EAST";
            }
            else {
                dir1="WEST";
            }

    return dir1;
}

private String findLatitude(double y1, double y2) {

            double w1=y1, w2=y2;
            String dir2;

            //using the latitudes
            if(w2>w1)
            {
                dir2="NORTH";
            }
            else
            {
                dir2="SOUTH";
            }

    return dir2;
}

public String getIpAddress() {
    String ip = "";
    try {
        Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
                .getNetworkInterfaces();
        while (enumNetworkInterfaces.hasMoreElements()) {
            NetworkInterface networkInterface = enumNetworkInterfaces
                    .nextElement();
            Enumeration<InetAddress> enumInetAddress = networkInterface
                    .getInetAddresses();
            while (enumInetAddress.hasMoreElements()) {
                InetAddress inetAddress = enumInetAddress
                        .nextElement();

                if (inetAddress.isSiteLocalAddress()) {
                    ip += "Server running at : "
                            + inetAddress.getHostAddress();
                }
            }
        }

    } catch (SocketException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        ip += "Something Wrong! " + e.toString() + "\n";
    }
    return ip;
}

My client code is this:

private static Socket socket;
double x1,y1,x2,y2;
int sp;
String dir1, dir2;
String message;
Client(){}
public void run()
{
    try
    {
        int port = 8080;
        String address="192.168.1.65";
        socket = new Socket(address, port);

        //Send the message to the server
        OutputStream os = socket.getOutputStream();
        OutputStreamWriter osw = new OutputStreamWriter(os);
        BufferedWriter bw = new BufferedWriter(osw);



        String sendMessage;
        sendMessage= Double.toString(x1)+"_"+Double.toString(y1)+"_"+Integer.toString(sp)+"_"+dir1+"_"+dir2+"_"+Double.toString(x2)+"_"+Double.toString(y2);
        bw.write(sendMessage);
        bw.flush();


        //Get the return message from the server
        InputStream is = socket.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        message = br.readLine();
    }
    catch (Exception exception)
    {
        exception.printStackTrace();
    }
    finally
    {
        //Closing the socket
        try
        {
            socket.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}

public void setElements(double z1, double w1, double z2, double w2, int speed, String direction1, String direction2){

    x1=z1;
    y1=w1;
    x2=z2;
    y2=w2;
    sp=speed;
    dir1=direction1;
    dir2=direction2;

}

public String getMessage(){
    return message;
}

I would appreciate any help, thank you in advance!

Use netcat to diagnose. There is a netcat executable (or binary) for just about every operating system. It is also available in all major package managers "apt-get", "yum", macports and others. The terminal command is nc .

To Listen:

    nc -l <port>

To Request:

    nc localhost 8080

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