客户端 - 服务器连接/通信(Java套接字)

时间:2016-10-20 15:47:53

标签: java android sockets server client

我正在尝试为Android收集坐标的应用程序(客户端),它计算用户移动的速度,然后将它们发送到另一个Android应用程序(服务器)。在服务器上我检查用户是否运行得太快并且我发送消息(从服务器到客户端)以减慢速度,我还检查两个用户是否可能崩溃并且我发送了相应的消息。

我的问题是,当两个应用程序似乎工作正常(客户端正在运行并显示速度,服务器正在运行并显示正在侦听的端口及其IP)时,服务器不会收到我从客户端发送的数据。我无法理解有什么不对。我不确定服务器是否没有接收或客户端没有发送。

我的服务器代码是:

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

我的客户端代码是:

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

我将不胜感激,谢谢你们!

1 个答案:

答案 0 :(得分:0)

使用netcat进行诊断。几乎每个操作系统都有一个netcat可执行文件(或二进制文件)。它也适用于所有主要的包装经理和#34; apt-get&#34;,&#34; yum&#34;,macports等。终端命令为nc

倾听:

    nc -l <port>

要求:

    nc localhost 8080