如何使用Java的Socket实现一个简单的服务呢?
下文是笔者讲述的使用java代码编写的Socket服务的方法分享,如下所示:
当接收到客户端请求后,打印出客户端IP地址,
并向客户端发送hello字符串
然后关闭客户端连接
继续等待下一个客户端连接
服务器端
编写一个服务端,当接收到客户端请求后,打印出客户端IP地址,
并向客户端发送hello字符串
然后关闭客户端连接
继续等待下一个客户端连接
客户端
编写一个Socket连接Socket服务端 将接收到的服务器端数据,并打印注意事项: 当存在缓冲的输入和输出流时,需使用flush()
服务器端代码
package com.java265.other; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class HelloService extends Thread { private ServerSocket serverSocket; public HelloService(int port) throws IOException { serverSocket = new ServerSocket(port); } public void run() { try { while(true) { System.out.println("等待客户端连接端口: " + serverSocket.getLocalPort()); Socket client = serverSocket.accept(); // 阻塞等待中 System.out.println("客户端连接地址 " + client.getRemoteSocketAddress()); DataOutputStream dos = new DataOutputStream(client.getOutputStream()); byte[] msg = "欢迎你来到java265.com".getBytes(); dos.write(msg, 0, msg.length); dos.close(); client.close(); } } catch(Exception e) { e.printStackTrace(); } } public static void main(String[] args) { try { HelloService service = new HelloService(8888); service.start(); } catch (IOException e) { e.printStackTrace(); } } }服务器在端口8888监听并等待连接,使用Java Thread来实现服务器端启动。
客户端代码
package com.java265.other; import java.io.DataInputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; public class HelloClient { private int clientNumber; private SocketAddress address; public HelloClient(int clientNum) { clientNumber = clientNum; } public void setupClients(String serverHostName, int port) throws IOException { address = new InetSocketAddress(serverHostName, port); for(int i=0; i<clientNumber; i++) { System.out.println(); System.out.println("start client No. " + (i+1)); Socket socket = new Socket(); socket.connect(address); DataInputStream bufferedReader = new DataInputStream(socket.getInputStream()); byte[] cbuff = new byte[256]; char[] charBuff = new char[256]; int size = 0; while( (size = bufferedReader.read(cbuff))> 0) { convertByteToChar(cbuff, charBuff, size); System.out.println(charBuff); } bufferedReader.close(); socket.close(); } } private void convertByteToChar(byte[] cbuff, char[] charBuff, int size) { for(int i=0; i<charBuff.length; i++) { if(i < size) { charBuff[i] = (char)cbuff[i]; } else { charBuff[i] = ' '; } } } public static void main(String[] args) { try { HelloClient client = new HelloClient(10); client.setupClients("localhost", 9999); } catch (IOException e) { e.printStackTrace(); } } }
启动100个客户端去连接服务器端 接受到服务器端信息后 关闭客户端连接
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。