服务器端
1.创建一个ServerSocket对象,指定端口
2.监听客户端请求accept()
3.打开输入流,接收用户请求
4.关闭资源
public static void main(String[] args) { try { ServerSocket serverSocket = new ServerSocket(8000); Socket socket = serverSocket.accept(); InputStream is = socket.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String information = null; while((information = reader.readLine())!= null) { System.out.printf("我是服务器端,接收的数据为:%S",information); } reader.close(); is.close(); socket.close(); serverSocket.close(); } catch (IOException e) { // TODO: handle exception e.printStackTrace(); } }
客户端
1.创建一个Socket对象
2.打开输出流,发送用户请求
3.关闭资源
public static void main(String[] args) { try { Socket socket = new Socket("localhost", 8000); OutputStream os = socket.getOutputStream(); String info = "账户:admin,密码:123456"; os.write(info.getBytes()); os.close(); socket.close(); } catch (IOException e) { // TODO: handle exception } }