亲宝软件园·资讯

展开

Java怎样实现简单后台访问并获取IP

wangchw 人气:0

后台服务端

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
 

public class Server {
  public static void main(String[] args) throws IOException {
    ServerSocket s = new ServerSocket(1122);//服务器端口号
    Socket ss = s.accept();
//    获取IP访问者IP地址
    String cip = ss.getInetAddress().getHostAddress();
//     接收信息获取访问姓名身份同时向访问者问好
    String msg = String.format("%s:Hello\s\n", "wo", cip);
    OutputStream os = ss.getOutputStream();
    PrintWriter out = new PrintWriter(os);
    out.write(msg);
    out.flush();
    System.out.println("有人连线了: " + cip);
//    读取信息
    InputStream is = ss.getInputStream();
    System.out.println(new String(is.readAllBytes()));
    System.out.println(ss.isConnected());
    os.close();
  }
}

客户端

import java.io.*;
import java.net.Socket;
public class Client {
  public static void main(String[] args) throws IOException {
    Socket client = new Socket("192.168.1.16", 1122);//服务器端口号1122,IP也可以自定义访问也可以在IP那里输入localhost访问本机
    if (client.isConnected()) {
//      接收信息
      InputStream is = client.getInputStream();
      BufferedReader br=new BufferedReader(new InputStreamReader(is));
      System.out.println(br.readLine());
//        向服务器发送个人信息
      String msg = "学生:xxx\r\n";//名字可以定义
      OutputStream os = client.getOutputStream();
      os.write(msg.getBytes());
      os.flush();
      System.out.println(client.isConnected());
      System.out.println(client.isClosed());
      is.close();
      os.close();

    }
  }
}

后台接收的信息


客户端接收的信息


加载全部内容

相关教程
猜你喜欢
用户评论