具体的代码如下:
服务器Socket
*****************************************************************************
public class Server extends ServerSocket { private static final int SERVER_PORT = 10000; public Server() throws IOException { super(SERVER_PORT); try{ System.out.println("启动服务器"); while(true){ Socket socket = this.accept(); new ServerThread(socket);//每当收到一个socket就创建一个线程 } }catch(IOException e){ e.printStackTrace(); } finally{ this.close(); } }
public static void main(String args[]) throws IOException{ new Server(); } }
****************************************************************************************************
线程类
public class ServerThread extends Thread{ private Socket client; private BufferedReader in; public ServerThread(Socket client) { super(); this.client = client; try { this.start(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void run() { try { in = new BufferedReader(new InputStreamReader( client.getInputStream()));// 得到客户端的输入流 System.out.println(in.readLine());//控制台输入信息 client.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
**********************************************************************************************************
客户端类
public class Client { private Socket socket; private PrintWriter out;//相当于向外写文件,所以用out private static int count = 1; public Client(String clientName) { this.connect(); } public Client() { this(null); this.connect(); } public void connect() { try { socket = new Socket("127.0.0.1", 10000); System.out.println("请输入信息:"); out = new PrintWriter(socket.getOutputStream(), true); BufferedReader line = new BufferedReader(new InputStreamReader( System.in));// 从控制台输入信息 out.println(line.readLine());// 输入信息到服务器 out.close(); socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * @param args */ public static void main(String[] args) { new Client(); } }
****************************************************************************************
测试方法,先运行Server,再运行Client