Java 套接字=新套接字(serverAddr,端口);
当我说socket=newsocket(serverAddr,PORT)时;在android中,打开的是哪种类型的套接字?UDP套接字还是TCP套接字? 我正在尝试从我的android发送数据,并从我的PC读取数据。我正在从UDP接收器C#script(Unity3D)读取数据。但我的android报告连接超时异常Java 套接字=新套接字(serverAddr,端口);,java,android,unity3d,Java,Android,Unity3d,当我说socket=newsocket(serverAddr,PORT)时;在android中,打开的是哪种类型的套接字?UDP套接字还是TCP套接字? 我正在尝试从我的android发送数据,并从我的PC读取数据。我正在从UDP接收器C#script(Unity3D)读取数据。但我的android报告连接超时异常 我的问题是,android打开的是什么类型的套接字?您使用的是tcp。对于使用udp套接字,请使用以下示例代码: 服务器代码: public class udp_server { p
我的问题是,android打开的是什么类型的套接字?您使用的是tcp。对于使用udp套接字,请使用以下示例代码: 服务器代码:
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
谢谢,这很有帮助。我试着从电脑上实时读取手机上的加速计数据。我打开了一个tcp连接,通过WiFi获取数据流。但也有一些滞后。有什么更好的方法可以做到这一点?wifi是正确的方法,还是我应该试试蓝牙?最终,我的手机应该像无线鼠标一样传输数据。