-1
私はソケットプログラミングの新人です。私は、ローカルファイルからデータを読み込み、ソケットによってサーバーに送信したいと思います。同じマシン(クライアントとサーバーが1台のコンピューターにある)でテストする場合、それは機能します。しかし、リモートマシンのサーバーをテストすると、クライアントマシンから取得する必要があるデータが得られませんでした。誰でも私のコードを見るのを助けることができますか?ありがとう!Javaソケット:データは転送されません
public class GreetingClient{
private Socket socket;
public GreetingClient(String serverName, int port) throws UnknownHostException, IOException {
this(new Socket(serverName,port));
}
public GreetingClient(Socket socket) {
this.socket = socket;
}
public static void main(String[] args) {
String hostname;
int port;
if (args.length == 2) {
hostname = args[0];
port = Integer.parseInt(args[1]);
} else {
hostname = "localhost";
port = 6066;
}
System.out.println("Connecting to " + hostname + " on port " + port);
String filePath ="C:/Users/Documents/file.xml";
GreetingClient c;
try {
c = new GreetingClient(hostname, port);
c.send(filePath);
} catch (IOException e) {
e.printStackTrace();
}
}
public void send(String filePath) throws IOException {
InputStream inputStream = new FileInputStream(filePath);
IOUtils.copy(inputStream , this.socket.getOutputStream());
this.socket.getOutputStream().flush();
this.socket.shutdownOutput();
System.out.println("Finish sending file to Server.");
}
}
public class GreetingServer extends Thread {
private ServerSocket serverSocket;
public GreetingServer(int port) throws IOException {
serverSocket = new ServerSocket(port);
}
public void run() {
while (true) {
try {
System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("Just connected to " + server.getRemoteSocketAddress());
if (!server.isClosed()) {
DataOutputStream out = new DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for connecting to " + server.getLocalSocketAddress() + "\n Goodbye!");
}
DataInputStream in = new DataInputStream(server.getInputStream());
if (in != null) {
Upload upload = parseXmlToJaxb(in);
long clientID = upload.getClientID();
System.out.println("Client "+clientID);
server.close();
} else {
System.out.println("Unknown Message Received at " + _dateTimeFormatter.format(new Date()));
}
} catch (SocketTimeoutException s) {
System.out.println("Socket timed out!");
break;
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}
*私は*すべきデータを得られませんでした。 - どのように?間違ったデータですか?データなし?データが壊れていますか? –
私はクライアントとサーバーのちょうど左になるまでたくさんのコードを取り除きました。クライアントは単純なバイトをサーバーに送り、それが動作するかどうかを確認します。その後、もう一方のコードをゆっくりと再追加します。 –