序言:
1.知道局域网络对战,但是想在局域网全球的网络下进行的游戏的。却一直没有思路。最近同为学习的朋友,找了很多资料弄明白了怎么去连接云服务器上运行的监听代码。
2.前提:需要一个云服务器;
1.服务端设置:云服务器需要设置出、入规则
入方向规则,开放端口8088
出方向规则,开放端口 8088
上述两步完成后,相当于我们把指定的端口打开了;
2.找到自己的服务器的两个ip
公网ip : 1.1.1.1
私网ip : 172.1.1.1
3.编写的服务端:GreetingServer .java
import java.io.*; import java.net.*; public class GreetingServer extends Thread{ private ServerSocket serverSocket; public GreetingServer(int port) throws IOException{ InetAddress adr = Inet4Address.getByName("服务器的私网ip"); serverSocket = new ServerSocket(port,50,adr); //port 指的是端口号 8088 serverSocket.setSoTimeout(50000); } public void run(){ while(true){ try { System.out.println("waitting link:"+serverSocket.getLocalSocketAddress() +"--->"+ serverSocket.getLocalPort()+"..."); Socket server =serverSocket.accept(); System.out.println("server host adress:"+server.getRemoteSocketAddress()); DataInputStream in = new DataInputStream(server.getInputStream()); System.out.println(in.readUTF()); DataOutputStream out = new DataOutputStream(server.getOutputStream()); out.writeUTF("Thinks connect me:"+ server.getLocalSocketAddress() +"\n Goodbye!"); server.close(); } catch (SocketTimeoutException s) { //TODO: handle exception System.out.println("Socket timed out!"); break; }catch(IOException e){ e.printStackTrace(); break; } } } public static void main(String[] args) { int port = Integer.parseInt(args[0]); try { Thread t = new GreetingServer(port); t.run(); } catch (Exception e) { //TODO: handle exception e.printStackTrace(); } } }
4.编写客户端代码 GreetingClient.java
import java.net.*; import java.io.*; public class GreetingClient{ public static void main(String[] args) { String serverName = args[0]; int port = Integer.parseInt(args[1]); try { System.out.println("link host:"+serverName +",port:"+port); Socket client = new Socket(serverName,port); System.out.println(" Sever host adress:"+client.getRemoteSocketAddress()); OutputStream outToServer =client.getOutputStream(); DataOutputStream out = new DataOutputStream(outToServer); out.writeUTF("Hello Form "+ client.getLocalSocketAddress()); InputStream inFromServer = client.getInputStream(); DataInputStream in = new DataInputStream(inFromServer); System.out.println("Sever CallBack :"+in.readUTF()); client.close(); } catch (Exception e) { //TODO: handle exception e.printStackTrace(); } } }
5.执行代码
//服务端 (需要安装java sdk)
# javac GreetingServer.java //编译代码
# java GreetingServer 8088 //执行代码
//客服端 (同样也需要java sdk)
#javac GreetingClient.java
#java GreetingClient 公网ip 8088
6.输出内容如下
内容点两个
1.客服端 使用公网 ip 和指定端口号进行访问
2.服务端 使用私网ip 和端口号设置
3.修改安全组,开放指定 端口和ip的出入