简单的java socket通讯

<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script> /** class:SocketTest_SvrClit author:chengyun date: with:to test socket---server program; **/ import java.net.*; import java.io.*; public class SocketTest_Server { public static void main(String[] args) throws UnknownHostException,IOException,ConnectException { ServerSocket aServerSocket=new ServerSocket(3434); Socket aServer=null; try { aServer=aServerSocket.accept(); try { BufferedReader input=new BufferedReader(new InputStreamReader(System.in)); BufferedReader in=new BufferedReader(new InputStreamReader(aServer.getInputStream())); PrintWriter out=new PrintWriter(new OutputStreamWriter(aServer.getOutputStream())); String serverstring=null; String clientstring=null; System.out.println("hello! enter the bye to exit."); System.out.print("Server:wait client"); serverstring=input.readLine(); boolean done=false; while(!done) { if(serverstring !=null) { out.println(serverstring); out.flush(); } clientstring=in.readLine(); if(clientstring !=null) System.out.println("client:" clientstring); System.out.print("server:"); serverstring=input.readLine(); if(serverstring.equals("bye")) done=true; } } catch(Exception e) { System.out.println(e.getMessage()); } finally { aServer.close(); } } catch(Exception e) { System.out.println(e.getMessage()); } finally { aServerSocket.close(); } } } /** class:SocketTest_SvrClit author:chengyun date: with:to test socket---client program; **/ import java.net.*; import java.io.*; public class SocketTest_SvrClit { public static void main(String[] args) throws UnknownHostException,IOException,ConnectException { Socket aClient=null; aClient=new Socket("192.168.0.8",3434); //InetAddress.getLocalHost() try { BufferedReader input=new BufferedReader(new InputStreamReader(System.in)); BufferedReader in=new BufferedReader(new InputStreamReader(aClient.getInputStream())); PrintWriter out=new PrintWriter(new OutputStreamWriter(aClient.getOutputStream())); String clientString=null; String serverString=null; System.out.println("hello!enter bye to exit."); boolean done=false; while(!done) { serverString=in.readLine(); if(serverString !=null) System.out.println("Server:" serverString); System.out.print("client:"); clientString=input.readLine(); if(clientString.equals("bye")) done=true; if(clientString !=null) { out.println(clientString); out.flush(); } } in.close(); out.close(); } catch(Exception e) { System.out.println(e.getMessage()); } finally { aClient.close(); } } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值