私はアンドロイドとJavaを学び始めたばかりです。今、私はアンドロイドとPCの間の単純なudp接続を確立しようとしています. しかし、私のサーバーは Android からメッセージを受信していないようです。ポートをリッスンしているコンソールに書いた1行...そして何も起こりません。最初に、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());
}
}
}