Window connect to Linux over TCP/IP by java.

  • 1. Create a client.
  • 2. Create a server.
  • 3. Close firewall on Linux.


1. Create a client

package com.chris.client;

import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;


import java.net.UnknownHostException;

public class Client {
	
	public static void main(String[] args) throws UnknownHostException, IOException {
		
		Socket client = new Socket( "192.168.104.164", 8888 );
		System.out.println( client.isBound() );
		PrintStream writer = new PrintStream( client.getOutputStream() );
		writer.println(" HelloLinux, I'm come from Windows environment");
		writer.close();
	}

}


2. Create a Server

package com.chris.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

    public void createServer() throws IOException, InterruptedException {
        
        ServerSocket server = new ServerSocket( 8888 );
        
        
        Socket s = server.accept();
        BufferedReader reader = new BufferedReader(new InputStreamReader(s
                .getInputStream()));
        

        char[] buffer = new char[1024];
        StringBuilder sb = new StringBuilder(1024 * 1024);
        int size = -1;
        while ((size = reader.read(buffer)) != -1) {
            String temp = new String(buffer, 0, size);
            sb.append(temp);
        }
        System.out.println( sb.toString());
        reader.close();
        
    }

    public static void main(String[] args) {

        Server server = new Server();
        try {
            server.createServer();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}


以上的程序如果只是在本地测试,那么可以正常的通过, 但是当我把服务器程序放到Linux系统下(另外一台机器), 而Client部分放到Windows平台下跑时,系统就包下面的异常了
Exception in thread "main" java.net.NoRouteToHostException: No route to host: connect
	at java.net.PlainSocketImpl.socketConnect(Native Method)
	at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
	at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
	at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
	at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
	at java.net.Socket.connect(Socket.java:519)
	at java.net.Socket.connect(Socket.java:469)
	at java.net.Socket.<init>(Socket.java:366)
	at java.net.Socket.<init>(Socket.java:179)
	at com.chris.client.Client.main(Client.java:14)


后面通过查找相关资料, 发现是Linux防火墙没有关的的原因导致的。
3. Close firewall on Linux

到Shell窗口下,键入service iptables stop, 重新联接, OKay了

如果要重新启动防火墙则输入service iptables start

总结:

  是否有其它的方式没有, 如果有, 请不赐教:)

你可能感兴趣的:(java,linux,.net,socket,防火墙)