我刚开始学习android&java。现在我正在尝试在 android 和 pc 之间建立简单的 udp 连接。但看起来我的服务器没有收到来自 android 的消息;它在控制台中编写的一行监听端口......然后什么也没有发生。首先我在 netbeans 中运行服务器代码,而不是在 android 模拟器中运行我的客户端。把招工广告!
client:
package com.asd.soed;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Thread thread=new Thread (new Client());
thread.start();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
package com.asd.soed;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import android.util.Log;
public class Client implements Runnable {
Client()
{
run();
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
String messageStr = "Hello Android!";
int server_port = 9999;
DatagramSocket s = new DatagramSocket();
InetAddress local = InetAddress.getByName("127.0.0.1");
int msg_length = messageStr.length();
byte[] message = messageStr.getBytes();
DatagramPacket p = new DatagramPacket(message, msg_length, local,
server_port);
s.send(p);
} catch (Exception e) {
}
}
}
server:
package serv;
/**
*
*/
import java.net.*;
import java.util.Date;
class Serv
{
private static final int PORT = 9999;
public static void main(String args[])
throws Exception
{
System.out.println("UDP Server Listening on port# " + PORT);
byte[] buffer = new byte[65536];
DatagramSocket serverSocket = new DatagramSocket(PORT);
DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);
for (;;)
{
serverSocket.receive(receivePacket);
System.out.println((new Date().toString()) + ": " +"Received " + receivePacket.getLength() +
" bytes from " + receivePacket.getAddress() + ":" + receivePacket.getPort() + "...");
String value = new String(buffer, 0, receivePacket.getLength());
System.out.println(value);
receivePacket.setLength(buffer.length);
byte[] b = "Hello from UDP Server".getBytes();
DatagramPacket sendPacket = new DatagramPacket(b, b.length, receivePacket.getAddress(), receivePacket.getPort());
serverSocket.send(sendPacket);
System.out.println((new Date().toString()) + ": " +"Sent Response of " + b.length + "b to " +receivePacket.getAddress() + ":" + receivePacket.getPort());
}
}
}