标签:finally date bsp server etc 客户端 内容 ade pen
一个超级简单的socket实现通信
SocketServer
public class SocketServer { public static void main(String[] args) { makeSocketSerer(); } public static void makeSocketSerer(){ ServerSocket serverSocket = null; try{ //启动一个服务,指定端口 serverSocket = new ServerSocket(8888); while(true){ //等待一个接收请求 Socket socket = serverSocket.accept(); //lamda表达式 new Thread(()->{ try { //读取客户端带来的数据 BufferedReader bufferReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); //返回给客户端数据 PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(socket.getOutputStream())); while(true){ String getClientDate = bufferReader.readLine(); if(getClientDate == null){ break; } System.out.println("server端接收到的消息内容: "+getClientDate); printWriter.println("Hello socket Client!!!"); printWriter.flush(); } printWriter.close(); bufferReader.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }).start(); } }catch(Exception e){ e.printStackTrace(); }finally{ if(serverSocket != null){ try { serverSocket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
SocketClient
public class SocketClient { public static void main(String[] args) { makeSocketClient(); } public static void makeSocketClient(){ try { //定一个ip和端口的socket连接 Socket socket = new Socket("localhost", 8888); //接收服务端返回的消息 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); //往服务端发送消息 PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true); printWriter.println("Hello socket Server !!!"); while(true){ String getServerData = bufferedReader.readLine(); if(getServerData == null){ break; } System.out.println("Client接收到的数据: "+getServerData); } printWriter.close(); socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
标签:finally date bsp server etc 客户端 内容 ade pen
原文地址:https://www.cnblogs.com/liqiang0728/p/11109999.html