日期:2014-05-20 浏览次数:20829 次
package Socket_Test1; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.Socket; public class ClientTest { public static void main(String[] args) { ClientTest ct = new ClientTest(); } public ClientTest() { Socket s = null; BufferedWriter bw = null; OutputStreamWriter osw = null; BufferedReader br= null; InputStreamReader isr = null; try { s = new Socket("127.0.0.1",8092); //req server osw =new OutputStreamWriter(s.getOutputStream()); bw = new BufferedWriter(osw); bw.write("你是谁?"); bw.flush(); //res server isr = new InputStreamReader(s.getInputStream()); br= new BufferedReader(isr); String res =br.readLine(); System.out.println("服务端发来:"+ res); }catch(Exception ex) { ex.printStackTrace(); } finally { try { br.close(); isr.close(); bw.close(); osw.flush(); osw.close(); s.close(); } catch (IOException e) { e.printStackTrace(); } } } }
package Socket_Test1; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.ServerSocket; import java.net.Socket; public class ServerTest{ public static void main(String[] args) { ServerTest st = new ServerTest(); } public ServerTest() { ServerSocket ss = null; Socket s = null; BufferedReader br= null; InputStreamReader isr = null; BufferedWriter bw = null; OutputStreamWriter osw = null; try{ ss = new ServerSocket(8092); System.out.println("服务端启动……"); s = ss.accept(); //res client isr = new InputStreamReader(s.getInputStream()); br= new BufferedReader(isr); String res =br.readLine(); System.out.println("客户端发来:"+ res); //req client osw =new OutputStreamWriter(s.getOutputStream()); bw = new BufferedWriter(osw); bw.write("我是服务器!"); bw.flush(); }catch(Exception ex) { ex.printStackTrace(); } finally { try { bw.close(); osw.close(); br.close(); isr.close(); ss.close(); } catch (IOException e) { e.printStackTrace(); } } } }