Java socket是一个必备知识,很多人不知道如何用Java写socket客户端向服务器端发送并返回消息,下面小编就来教大家学习Java TCP的使用示例,先来看socket服务器端的代码:
package com.tpyyes; import java.io.*; import java.net.ServerSocket; import java.net.Socket; public class TCPServer { public static void main(String[] args) throws IOException { //设定服务器端口,ip不设置表示默认的本机ip ServerSocket server = new ServerSocket(8888); while(true){ Socket clientSocket = server.accept(); BufferedReader br=new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String msg = br.readLine(); //输出socket客户端发送进来的消息 System.out.println(msg); clientSocket.shutdownInput(); //返回消息给socket客户端 PrintWriter writer = new PrintWriter(clientSocket.getOutputStream()); writer.println(clientSocket.getPort()+"服务器返回:"+msg); writer.flush(); //收到此消息退出socket服务器端 if(msg.equals("exit")){ server.close(); } } } }
socket客户端代码:
package com.tpyyes; import java.io.*; import java.net.Socket; public class TCPClient { public static void main(String[] args) throws IOException { //绑定服务器端IP与端口并发送消息 Socket socket = new Socket("127.0.0.1", 8888); OutputStream out = socket.getOutputStream(); out.write("我是客户端".getBytes()); socket.shutdownOutput(); //输出socket服务器端返回的消息 InputStream inputStream = socket.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); System.out.println(reader.readLine()); socket.close(); } }
我们要先运行Java socket(TCP)服务器端代码,然后再运行TCP客户端,输出结果分别如下:
socket服务器端马上收到客户端发送进来的消息:
socket客户端接收来自服务器端反馈的消息: