我想寫一個簡單的客戶端服務器程序。客戶端和服務器都在java中編程,並通過接入點作爲局域網連接,服務器是我的筆記本電腦,客戶端是我的android設備。下面是客戶端(安卓)代碼:Java套接字接收器工作在Linux上,但不是在Windows上
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上嘗試時,服務器程序沒有顯示任何響應。那麼,阻礙服務器收聽或接受客戶端發送的數據有什麼麻煩?
你可以嘗試關閉你的防火牆嗎? –
嘿謝謝你,那很好。但是有什麼比關閉Windows防火牆更好的方法嗎?我正在使用Windows 7. – cakil