我正在尝试编写一个简单的客户端服务器程序。客户端和服务器都用 java 编程并通过接入点作为局域网连接,服务器是我的笔记本电脑(计算机),客户端是我的 android 设备。这是客户端(android)的代码:
package com.caisar.andronet;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class Main extends Activity {
private Button mSendButton;
private EditText ipInput;
private EditText portInput;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mSendButton = (Button) findViewById(R.id.button1);
ipInput = (EditText) findViewById(R.id.editText1);
portInput = (EditText) findViewById(R.id.editText2);
mSendButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
sendPacket();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public void sendPacket() throws IOException
{
int port = Integer.parseInt(portInput.getText().toString());
InetAddress address = InetAddress.getByName(ipInput.getText().toString());
String message = "Ini adalah caisar oentoro";
byte[] messages = message.getBytes();
DatagramSocket socket = new DatagramSocket();
DatagramPacket packet = new DatagramPacket(messages, messages.length, address, port);
socket.send(packet);
socket.close();
}
}
这是服务器程序:
import java.net.*;
import java.io.*;
class DatagramReceiver{
public static void main(String[] args){
try
{
int MAX_LEN = 40;
int localPort = Integer.parseInt(args[0]);
DatagramSocket socket = new DatagramSocket(localPort);
byte[] buffer = new byte[MAX_LEN];
DatagramPacket packet = new DatagramPacket(buffer, MAX_LEN);
socket.receive(packet);
String message = new String(buffer);
System.out.println(message);
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
问题是,在 Ubuntu 上尝试服务器程序时,它运行良好,没有任何问题,但是当我在 Windows 上尝试时,服务器程序没有显示任何响应。那么“阻止”服务器侦听或接受客户端发送的数据的麻烦是什么?