02.1、建立Server(保持这个TankServer一直运行)
1 package server; 2 public class TankServer { 3 public static void main(String[] args) { 4 try { 5 // new一个ServerSocket对象,并时时刻刻监听着7575端口 6 ServerSocket ss = new ServerSocket(7575); 7 while(true) { 8 // 接受Socket信息 9 Socket s = ss.accept(); 10 System.out.println("TankServer.java:监听到" + s.getInetAddress() + ":" + s.getPort()); 11 } 12 } catch (IOException e) { 13 e.printStackTrace(); 14 } 15 } 16 }
02.2、建立Client(新建一个NetClient模型)
package client; public class NetClient { //Client连接Server public void connect(String IP, int port) { try { // IP地址与端口 Socket s = new Socket(IP, port); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
02.3、使Client与Server连接()
package client; public class GameClient extends Frame { //新建一个网络客户端模型 NetClient nc = new NetClient(); //实现与TankServer连接 this.nc.connect("192.168.1.1", TankServer.TCP_PORT); }
时间: 2024-11-05 20:36:25