Java--Socket,客户端,服务端双向通信
服务端:
import java.io.BufferedReader;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.InputStreamReader;import java.net.ServerSocket;import java.net.Socket;public class Server {public static final int PORT = 8000;//监听的端口号 public static void main(String[] args) { Server server = new Server(); server.init(); } public void init() { try { ServerSocket serverSocket = new ServerSocket(PORT); while (true) { Socket client = serverSocket.accept(); //一个客户端连接就开户一个线程处理 new Thread(new HandlerThread(client)).start(); } } catch (Exception e) { System.out.println("服务器异常: " + e.getMessage()); } } private class HandlerThread implements Runnable { private Socket client; public HandlerThread(Socket client) { this.client = client; } public void run() { try { //读取客户端数据 DataInputStream dis = new DataInputStream(client.getInputStream()); String reciver = dis.readUTF(); //处理客户端数据 System.out.println("客户端发过来的内容:" + reciver); //向客户端回复信息 DataOutputStream dos = new DataOutputStream(client.getOutputStream()); System.out.print("请输入:\t"); // 发送键盘输入的一行 String send = new BufferedReader(new InputStreamReader(System.in)).readLine(); dos.writeUTF(send); dos.close(); dis.close(); } catch (Exception e) { System.out.println("服务器异常: " + e.getMessage()); } finally { if (client != null) { try { client.close(); } catch (Exception e) { client = null; System.out.println("服务端异常:" + e.getMessage()); } } } } } }
客户端:
import java.io.BufferedReader;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.net.Socket;public class Client {public static final String IP = "localhost";//服务器地址 public static final int PORT = 8000;//服务器端口号 public static void main(String[] args) { while (true) { Socket client = null; try { //创建一个流套接字,连接到指定主机上的指定端口号 client = new Socket(IP, PORT); //读取服务器端数据 DataInputStream dis = new DataInputStream(client.getInputStream()); //向服务器端发送数据 DataOutputStream dos = new DataOutputStream(client.getOutputStream()); System.out.print("请输入: \t"); String send = new BufferedReader(new InputStreamReader(System.in)).readLine(); dos.writeUTF(send); String reciver = dis.readUTF(); System.out.println("服务器端返回过来的是: " + reciver); dos.close(); dis.close(); } catch (Exception e) { System.out.println("客户端异常:" + e.getMessage()); } finally { if (client != null) { try { client.close();} catch (IOException e) {client = null; System.out.println("客户端异常:" + e.getMessage()); } } } } } }