public classSocketClientDemo
{/*** 向指定的地址发送请求数据
*@paramipAddr
*@paramreqData*/
public voidsendReq(String ipAddr,String reqData)
{
Socket client= null;
BufferedReader br= null;
BufferedOutputStream bos= null;
String respStr= "";//设置字符集编码格式
String characterCoding = "GBK";//将ip:port 类型的字符串拆分
int dotPos = ipAddr.indexOf(":");
String ip= ipAddr.substring(0, dotPos).trim();int port = Integer.parseInt(ipAddr.substring(dotPos+1).trim());try{
client= newSocket(ip,port);//设置发送等待时间(单位:s)
client.setSoLinger(true, 5);//设置超时时间(单位:ms)
client.setSoTimeout(5000);//从client端获取输出流
bos = newBufferedOutputStream(client.getOutputStream());
bos.write(reqData.getBytes(characterCoding));
bos.flush();
br= new BufferedReader(newInputStreamReader(client.getInputStream()));
respStr=br.readLine();
System.out.println("respStr is:>>>>>>"+respStr);
}catch(UnknownHostException e)
{//TODO Auto-generated catch block
e.printStackTrace();
}catch(IOException e)
{//TODO Auto-generated catch block
e.printStackTrace();
}finally{if(br != null)
{try{
br.close();
}catch(IOException e)
{//TODO Auto-generated catch block
e.printStackTrace();
}
}if(bos!=null)
{try{
bos.close();
}catch(IOException e)
{//TODO Auto-generated catch block
e.printStackTrace();
}
}if(client!=null)
{try{
client.close();
}catch(IOException e)
{//TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}