我正在尝试在两个不同的系统上在Android模拟器上运行的客户端程序和服务器之间建立简单的UDP连接。服务器端很好,但客户端一直在崩溃。这是模拟器的问题吗?我应该重定向端口以使其工作吗?
客户端(在Android模拟器上):
package com.example.clientrecv;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity
{
public String text;
public int serverport=1234;
public byte[] message=new byte[1000];
public Button b;
public DatagramPacket p;
public DatagramSocket s;
public Toast t;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b=(Button) findViewById(R.id.button1);
try {
p = new DatagramPacket(message,message.length);
s = new DatagramSocket(serverport);
try {
s.receive(p);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
text= new String(message,0,p.getLength());
Log.d("hello","the message:"+text);
s.close();
// TODO Auto-generated method stub
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void showmsg()
{
t=Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG);
t.show();
}
}
SERVER SIDE: (on pc)
import java.io.*;
import java.net.*;
class serversend
{
public static void main(String args[]) throws Exception
{
String strmsg="Server says hello";
int serverport=1234;
int len=strmsg.length();
System.out.println("starting");
byte[] message=strmsg.getBytes();
try{
InetAddress local=InetAddress.getByName("localhost");
DatagramSocket s=new DatagramSocket();
DatagramPacket p=new DatagramPacket(message,len,local,serverport);
System.out.println("Running");
s.send(p);
System.out.println("Sent");
}catch(Exception e)
{
System.out.println("caught");
}
}
}
答案 0 :(得分:0)
有许多可用的示例可以帮助您使用UDP在服务器和客户端之间进行通信 要在这两者之间进行通信,应在服务器端添加客户端端口
InetAddress local = InetAddress.getByName("192.168.1.102");
答案 1 :(得分:0)
Android 3.0之后的版本不允许您在主UI线程中实现网络操作。您必须为此定义一个新的线程......以下是您可以执行此操作的方法:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//here you Set up you parameters and launch the thread (e.g):
this.newThread = new Thread(new mThread());
this.newThread.start();
/* Next you define your newThread's run method in wich all networking
operations must take place*/
class mThread implements Runnable {
public void run() {
// Do all networking tasks you need
}
}