之前写过一个Server Socket端。今天特意写了个client端。
java Socket 多线程Server端
两个结合起来,可以组成一个即时通讯的雏形。
package com.javaer.examples.socket; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; public class Client { static Socket server; /** * @param args * @throws IOException * @throws UnknownHostException */ public static void main(String[] args) throws UnknownHostException, IOException { server = new Socket(InetAddress.getLocalHost(), 2156); BufferedReader in = new BufferedReader(new InputStreamReader( server.getInputStream())); PrintWriter out = new PrintWriter(server.getOutputStream()); BufferedReader wt = new BufferedReader(new InputStreamReader(System.in)); while (true) { String str = wt.readLine(); out.println(str); out.flush(); System.out.println(in.readLine()); if (str.equals(‘‘end‘‘)) { break; } } server.close(); } }
首发于http://java-er.com - http://java-er.com/blog/java-socket-client/