java基础之使用socket进行cs通信
一、
二、Myserver.java
package socket; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; public class Myserver { public static void main(String[] args) throws IOException{ try { ServerSocket serverSocket = new ServerSocket(8888); System.out.println(123); Socket socket = serverSocket.accept(); System.out.println("客户端连接成功!"); InputStream input = socket.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); String info = null; while((info = reader.readLine())!=null){ System.out.println("I am server! 接收到的客户端消息:"+info); } socket.shutdownInput(); OutputStream out = socket.getOutputStream(); out.write("welcome client...".getBytes()); socket.shutdownOutput(); } catch (Exception e) { // TODO: handle exception } } }
三、Myclient.java
package com.example.demo; import java.io.*; import java.net.ServerSocket; import java.net.Socket; public class Myclient { public static void main(String[] args) { try { Socket socket = new Socket("localhost",8888); System.out.println("客户端启动"); OutputStream out = socket.getOutputStream(); out.write("hello socket!".getBytes()); socket.shutdownOutput(); InputStream input = socket.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); String info = null; while((info = reader.readLine())!=null){ System.out.println("I am client! 接收到的服务端端消息:"+info); } socket.shutdownInput(); } catch (Exception e) { // TODO: handle exception } } }
截图: