Sie von tcp verwendet.
Server Code: udp-Socket unter Beispielcode für die Verwendung von
public class udp_server
{
public static void main(String args[])
{
DatagramSocket sock = null;
try
{
//1. creating a server socket, parameter is local port number
sock = new DatagramSocket(7777);
//buffer to receive incoming data
byte[] buffer = new byte[65536];
DatagramPacket incoming = new DatagramPacket(buffer, buffer.length);
//2. Wait for an incoming data
echo("Server socket created. Waiting for incoming data...");
//communication loop
while(true)
{
sock.receive(incoming);
byte[] data = incoming.getData();
String s = new String(data, 0, incoming.getLength());
//echo the details of incoming data - client ip : client port - client message
echo(incoming.getAddress().getHostAddress() + " : " + incoming.getPort() + " - " + s);
s = "OK : " + s;
DatagramPacket dp = new DatagramPacket(s.getBytes() , s.getBytes().length , incoming.getAddress() , incoming.getPort());
sock.send(dp);
}
}
catch(IOException e)
{
System.err.println("IOException " + e);
}
}
//simple function to echo data to terminal
public static void echo(String msg)
{
System.out.println(msg);
}
}
-Client-Code:
public class udp_client
{
public static void main(String args[])
{
DatagramSocket sock = null;
int port = 7777;
String s;
BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
try
{
sock = new DatagramSocket();
InetAddress host = InetAddress.getByName("localhost");
while(true)
{
//take input and send the packet
echo("Enter message to send : ");
s = (String)cin.readLine();
byte[] b = s.getBytes();
DatagramPacket dp = new DatagramPacket(b , b.length , host , port);
sock.send(dp);
//now receive reply
//buffer to receive incoming data
byte[] buffer = new byte[65536];
DatagramPacket reply = new DatagramPacket(buffer, buffer.length);
sock.receive(reply);
byte[] data = reply.getData();
s = new String(data, 0, reply.getLength());
//echo the details of incoming data - client ip : client port - client message
echo(reply.getAddress().getHostAddress() + " : " + reply.getPort() + " - " + s);
}
}
catch(IOException e)
{
System.err.println("IOException " + e);
}
}
//simple function to echo data to terminal
public static void echo(String msg)
{
System.out.println(msg);
}
}
'Socket.connect' öffnet einen TCP-Socket UDP nutzen zu können, , müssen Sie ein 'DatagramSocket' – ControlAltDel
https://developer.android.com/reference/java/net/DatagramSocket.html – Fildor
Danke, dass Hilfe erstellen ed. Ich habe versucht, die Beschleunigungsmesserdaten auf meinem Telefon von meinem PC in Echtzeit zu lesen. Ich habe eine TCP-Verbindung geöffnet, um den Datenstrom über WiFi zu erhalten. Aber es gibt eine Verzögerung. Was ist ein besserer Weg, dies zu tun? Ist WiFi die richtige Methode, oder sollte ich Bluetooth ausprobieren? Letztendlich sollte mein Telefon Daten wie eine drahtlose Maus übertragen. – sujay