如何在自定义服务器中获取GPS设备数据?已完成配置与端口监听
Great job getting your GPS device configured to send data to your Windows server on port 7700! Your basic ServerSocket setup is a solid start—now let's expand it to actually read and process the incoming GPS data. Here's a step-by-step breakdown:
1. Read the Incoming Data Stream
Once a GPS device connects to your server, you need to read the data it sends. Most GPS devices use text-based protocols like NMEA 0183 (sentences starting with $), so we'll use a BufferedReader to read lines easily. Update your loop to handle each connection's input stream:
try (ServerSocket serverSocket = new ServerSocket(7700)) { System.out.println("Server is listening on port 7700"); int loop_counter = 1; while (true) { System.out.println("--- Refresh : "+loop_counter+" ---"); Socket socket = serverSocket.accept(); System.out.println("New GPS device connected!"); // Handle this connection in a separate thread (critical for multiple devices) new Thread(() -> handleGpsConnection(socket)).start(); loop_counter++; } } catch (IOException e) { System.err.println("Server error: " + e.getMessage()); } // Helper method to process a single GPS connection private static void handleGpsConnection(Socket socket) { try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) { String line; while ((line = in.readLine()) != null) { System.out.println("Received: " + line); // Parse and process the GPS data here parseNmeaSentence(line); } } catch (IOException e) { System.err.println("Connection closed or error: " + e.getMessage()); } finally { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } }
Key note: Using threads ensures your server can handle multiple GPS devices at once—without this, it would get stuck processing one device and ignore others.
2. Parse the GPS Data
If your device sends NMEA sentences (the most common format), each line follows a structured comma-separated format. Let's write a simple parser for the $GPGGA sentence (which contains core location data):
private static void parseNmeaSentence(String nmeaLine) { // Skip empty lines or non-NMEA data if (nmeaLine == null || !nmeaLine.startsWith("$")) return; switch (nmeaLine.substring(0, 6)) { case "$GPGGA": // Split the sentence into components String[] parts = nmeaLine.split(","); // Extract key data (adjust indices based on your device's NMEA version) String timestamp = parts[1]; // HHMMSS format String latRaw = parts[2]; // DDMM.MMMM format String latDir = parts[3]; // N/S String lonRaw = parts[4]; // DDDMM.MMMM format String lonDir = parts[5]; // E/W int fixQuality = Integer.parseInt(parts[6]); // 0 = no fix, 1 = valid fix if (fixQuality >= 1) { // Convert raw coordinates to decimal degrees double latitude = convertToDecimal(latRaw, latDir); double longitude = convertToDecimal(lonRaw, lonDir); System.out.printf("Valid Fix | Lat: %.6f, Lon: %.6f | Time: %s%n", latitude, longitude, timestamp); // Save this data to a database, send to another service, etc. } else { System.out.println("No valid GPS fix received"); } break; // Add cases for other NMEA sentences like $GPRMC if needed default: // Ignore unrecognized sentences break; } } // Convert DDMM.MMMM to decimal degrees private static double convertToDecimal(String rawCoord, String direction) { int degrees = Integer.parseInt(rawCoord.substring(0, rawCoord.indexOf('.') - 2)); double minutes = Double.parseDouble(rawCoord.substring(rawCoord.indexOf('.') - 2)); double decimal = degrees + (minutes / 60); // Adjust for southern/western hemispheres if (direction.equals("S") || direction.equals("W")) { decimal *= -1; } return decimal; }
If your device uses a proprietary binary protocol instead of NMEA, you'll need to refer to the manufacturer's documentation to decode the byte stream. Replace the BufferedReader with an InputStream and read raw bytes, then map them to the device's specific data structure.
3. Testing & Troubleshooting
- Simulate GPS data: Use a tool like Netcat (
nc localhost 7700) to paste sample NMEA sentences (e.g.,$GPGGA,123519,4807.038,N,00114.323,W,1,08,0.9,545.4,M,46.9,M,,*47) and verify your server parses them correctly. - Check firewalls: Ensure your Windows server's firewall allows incoming connections on port 7700.
- Handle disconnections: The try-with-resources block will automatically close streams/sockets if the device drops the connection, but adding logging will help you track device status.
内容的提问来源于stack exchange,提问作者mitu1234

