你從tcp使用。使用UDP套接字使用下面的示例代碼:
Server代碼:
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);
}
}
客戶端代碼:
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'打開一個TCP套接字 要使用UDP ,你需要創建一個'DatagramSocket' – ControlAltDel
https://developer.android.com/reference/java/net/DatagramSocket.html – Fildor
謝謝,那個幫助編輯。我試圖從我的電腦實時讀取手機上的加速度計數據。我打開了一個tcp連接來通過WiFi獲取數據流。但有一些滯後。有什麼更好的方法來做到這一點?無線是正確的方法,還是應該嘗試藍牙?最終,我的手機應該像無線鼠標一樣傳輸數據。 – sujay