服务端
import java.io.DataInputStream;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;public class Server2 {public static void main(String[] args) throws Exception{System.out.println("------------服务端启动--------------");//创建ServerSocket对象 为服务端注册端口ServerSocket socketServer =new ServerSocket(7777);//调用accept 方法等待客户端的链接请求Socket socket = socketServer.accept();//获取字节输入流InputStream ipt = socket.getInputStream();//把原始的字节输入流包装成数据输入流DataInputStream dis =new DataInputStream(ipt);while (true){//使用数据输入流 读取 用户发过来的信息try{String rs = dis.readUTF();System.out.println(rs);System.out.println(socket.getRemoteSocketAddress()); //客户端的地址System.out.println("------------------------");}catch (Exception e){System.out.println(socket.getRemoteSocketAddress()+"退出...");dis.close();socket.close();break;}}}
}
客户端
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;public class Client2 {public static void main(String[] args) throws Exception {//创建一个socket 对象 并同时请求与服务端程序的链接Socket socket = new Socket("127.0.0.1",7777);//从socket管道中获取字节流 用来发数据给服务端OutputStream os = socket.getOutputStream();//把低级的字节输出流 换成数据输出流DataOutputStream dos = new DataOutputStream(os);//开始写数据Scanner sc =new Scanner(System.in);while (true){System.out.println("user:");String msg =sc.nextLine();if("exit".equals(msg)){System.out.println("退出会话...");dos.close();//释放连接资源socket.close();break;}dos.writeUTF(msg);dos.flush();}}
}
结果