后台服务端 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) t
后台服务端
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(); } } }
后台接收的信息
客户端接收的信息
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。