实现一个socket的hello world程序需要一个服务端一个客户端,服务端建立监听,客户端去访问,当然通信是相互的,客户端也可以向服务端发送信息!这里我敲了一个例子是客户端访问服务端,服务端返回一个Hello World!!
import java.io.IOException; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class SocketServerStudy { public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; PrintWriter out = null; try { //实例一个socket服务端实例 serverSocket = new ServerSocket(6666); } catch (IOException e) { System.out.println("实例化服务端失败"+e); System.exit(1); } Socket clientsocket =null; try { //监听客户端的连接 clientsocket = serverSocket.accept(); } catch (IOException e) { System.out.println("创建监听失败"+e); System.exit(1); } try { out = new PrintWriter(clientsocket.getOutputStream(),true); out.println("hello world!!!!"); } catch (IOException e) { System.out.println("获取客户端输出流(写)失败"); System.exit(1); } clientsocket.close(); serverSocket.close(); } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket; import java.net.UnknownHostException; public class SocketClientStudy { public static void main(String[] args) throws IOException { Socket clientSocket = null; BufferedReader in = null; try { clientSocket = new Socket("localhost", 6666); in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); } catch (UnknownHostException e) { System.out.println("解析网址错误"); e.printStackTrace(); } catch (IOException e) { System.out.println("连接拒绝:服务器未启动"); e.printStackTrace(); } System.out.println(in.readLine()); in.close(); clientSocket.close(); } }
需要注意的是:需要先启动服务端,然后再启动客户端,否则是会报java.net.ConnectException: Connection refused: connect (拒绝连接)