日期:2014-05-19 浏览次数:20849 次
package com.haozhong.recharge.socket; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.nio.channels.SocketChannel; import java.util.Random; import com.haozhong.recharge.constants.Constants; // 取参例子 0030 lotterygetcs 101531 7 lt lot public class ClientTest { public static void main(String[] args){ SocketChannel channel = null ; try { channel = SocketChannel.open(); InetAddress add = InetAddress.getByName(Constants.LOTTERY_URL) ; InetSocketAddress isa = new InetSocketAddress(add,Constants.LOTTERY_PORT); channel.connect(isa) ; System.out.println("与服务器建立连接") ; /** * */ Socket socket = channel.socket() ; while(true){ InputStream is = socket.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); OutputStream os = socket.getOutputStream(); PrintWriter pw = new PrintWriter(os,true); String msg = null ; char[] cbuf = new char[1024]; byte[] b = null ; StringBuilder sb = new StringBuilder() ; String str = "" ; msg = "0013\ttest\t"+new Random().nextInt(1000000)+"" ; System.out.println(msg) ; pw.println(msg); while(true){ if (br.read(cbuf) == -1){ break; } sb.append(new String(cbuf)) ; str = sb.toString() ; b = str.getBytes() ; if(b.length >= 1024){ break ; } } System.out.println(str) ; Thread.sleep(5*1000) ; /*if(result != null && result != ""){ msg ="0032\tlotterygetcs\t33920001\t7\tlj\tlot\t" ; pw.println(msg); System.out.println(br.readLine()) ; msg = "0100\tlotterygetbulletin\t858939\t60\t33920001\tlot\t2009001\t" ; pw.println(msg) ; System.out.println(br.readLine()) ; }*/ } /*while((msg = r.readLine())!= null){ pw.println(msg); System.out.println(br.readLine()); if(msg.equals("bye")){ break ; } }*/ } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(channel != null){ try { channel.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }