本人用的是UDP,现在客户端不能发消息给服务器,不知道怎么回事代码如下:
客户端代码
public class ChatRoom extends Activity {
private EditText chattxt;
private TextView chattxt2;
private Button chatok;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chatroom);
findviews();
setonclick();
} public void findviews() {
chattxt = (EditText) this.findViewById(R.id.chattxt);
chattxt2 = (TextView) this.findViewById(R.id.chattxt2);
chatok = (Button) this.findViewById(R.id.chatOk);
} private void setonclick() {
chatok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
connecttoserver(chattxt.getText().toString());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}


 public void connecttoserver(String socketData) throws UnknownHostException, IOException
 {
 byte[] buf=new byte[500];
 socketData.getBytes(0,socketData.length(),buf,0);
 //连接服务器
 DatagramPacket  sendPacket=new DatagramPacket(buf, socketData.length(), new InetSocketAddress("10.0.2.2",5000));
 DatagramSocket sendSocket=new DatagramSocket( 9999);//有时候这里老报这里端口被占
 //发送数据包
 sendSocket.send(sendPacket);
 sendSocket.close();
   
 }
 
 public void receiveMessage()
 {
 try {
DatagramSocket receiveSocket=new DatagramSocket(5000);
 byte buf[]=new byte[500];
 DatagramPacket receivePacket=new DatagramPacket(buf, buf.length);
 
 while(true)
 {
 receiveSocket.receive(receivePacket);//接收数据包
 String msg=new String(receivePacket.getData(),0,receivePacket.getLength());
 this.chattxt2.append(msg+"\n");//显示接收到的信息
 }
 
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

 
 }
}请高手帮忙指点一下!!!

解决方案 »

  1.   

    UDP发送消息,发送端sendSocket不要绑定某个端口的
    你对sendSocket,receiveSocket都没有释放资源,建议ondestroy()和finally中执行sendSocket.disconnect();sendSocket.close();
      

  2.   

    //连接服务器
    DatagramPacket sendPacket=new DatagramPacket(buf, socketData.length(), new InetSocketAddress("10.0.2.2",5000));
    改为
    DatagramPacket sendPacket=new DatagramPacket(buf, socketData.length(), InetAddress.getByName("10.0.2.2",),5000);
    试试看吧