嘿,我一直在玩数据报类,我只是无法弄清楚为什么我的“服务器”不会从“客户端”接收数据包。数据报包和套接字的未知错误 - Java网络
我已经测试过服务器和客户端同时在我自己的PC上运行,它的工作原理完美,但如果我尝试将服务器移到另一台PC上,它不会。
现在我知道我必须做一些错误的套接字/地址/端口bleh ...我没有与网络工作过,所以我不知道很多。
这里的服务器代码:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.net.UnknownHostException;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.sql.Connection;
import java.util.ArrayList;
public class ServerThread extends Thread {
private boolean needsToRun;
private DatagramSocket socket;
public ServerThread() {
super();
needsToRun = true;
try {
socket = new DatagramSocket(4446);
}
catch (SocketException ex) {
ex.printStackTrace();
}
}
@Override
public void run() {
while(needsToRun) {
byte[] buf = new byte[265];
DatagramPacket packet = new DatagramPacket(buf,buf.length);
try {
socket.receive(packet);
}
catch(IOException e) {
e.printStackTrace();
}
String data = new String(packet.getData(),0,packet.getLength());
if(data != null)
System.out.println(data);
}
socket.close();
}
}
你会看到一些未使用的进口,但我只是剥离下来的代码,使其基本(大部分来自什么其实我是想在服务器做数据一旦收到,但我有这部分工作)。
这里的客户端代码:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
public class Main {
public static void main(String[] args) throws SocketException, UnknownHostException, IOException {
// get a datagram socket
DatagramSocket socket = new DatagramSocket();
// send request
String testInfo = "Hi";
byte[] buf = testInfo.getBytes();
/*This could possible be a point at which the code won't work.
*to get the bytes of the IP address of the computer I'm trying to run the server
*on I just did
* byte[] address = InetAddress.getLocalHost().getAddress();
* on the computer I was running the server on. I'm 95% sure that the IP addresses
* match.
*/
byte[] inet = {-64,-88,1,5};
InetAddress address = InetAddress.getByAddress(inet);
DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 4446);
try {
socket.send(packet);
}
catch(Exception e) {
e.printStackTrace();
}
socket.close();
}
}
代码的明显的部位,我检查,如端口和地址(见代码注释)。
所以我真正想要的是,如果你不明白为什么代码不会工作,那么你能告诉我一些可能出错的端口和什么东西(端口可能被关闭等等(除了我也很确定港口是开放的))。
感谢您的任何建议。
也许防火墙阻止了数据包?您是否尝试禁用每台计算机上的防火墙? – cdhowie 2010-11-15 03:49:28