日期:2014-05-17  浏览次数:20620 次

socket.connect(socketAddress,timeout ))
接口中的一个方法:向某个IP服务器下的某port 通过Socket 传入 request字符串,结果服务器处理返回 response字符串
问题:服务器端是怎么实现的?也就是说他是怎么监听有数据需要处理的s时候进行及时的处理?开始我想到ServerSocket但这是web工程主要怎么来实现呢?


 

Java code

public String reuqestTrade(String request, String url, String port,
            String encode) {
        String str = "ERROR";
        Socket socket = null;
        OutputStream os;
        InputStream is;
        try {
            socket = new Socket(); // 客户端给出IP和端口号
            SocketAddress socketAddress = new InetSocketAddress(url, 
                    Integer.parseInt(port.trim()));
            socket.connect(socketAddress, Integer.parseInt(Help
                    .getUrl("timeout")));
            log.info("socket(客服端未限制端口) 已连接-->" + url + ":" + port);
            is = socket.getInputStream();
            os = socket.getOutputStream();

            os.write(request.getBytes());
            os.flush();

            byte[] serByte = new byte[2048];
            String serverStr = null;
            int flag = is.read(serByte);
            if (flag != -1) {
                serverStr = new String(serByte);
            }
             log.info(" answer --> " + serverStr);
            return serverStr;
        } catch (UnknownHostException e) {
            log.error("systemerr", e);
            str = "ERROR";
            return str;
        } catch (IOException e) {
            log.error("systemerr", e);
            str = "ERROR";
            return str;
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    log.error("systemerr", e);
                    str = "ERROR";
                    return str;
                }
            }
        }
    }



------解决方案--------------------
对啊,线程,死循环,线程里面定时休眠就行了
public void run(){

while(true){

try{
//。。。。。。
}catch(Exception e){
}


}

}