socket的Read timed out问题

a21768541 2010-05-18 10:37:52

private static String sendSynMsg(String ipAddr, byte[] datas) throws Exception{
//解析服务器地址和端口号
int dotPos = ipAddr.indexOf(':');
String ip = ipAddr.substring(0, dotPos).trim();
int port = Integer.parseInt(ipAddr.substring(dotPos+1).trim());
InetSocketAddress endpoint = new InetSocketAddress(ip , port);
System.out.println("ip:"+ip+"port:"+port);
Socket socket = null;
OutputStream out = null;
InputStream in = null;
try {
socket = new Socket();
//设置发送逗留时间2秒
socket.setSoLinger(true, 2);
//设置InputStream上调用 read()阻塞超时时间2秒
socket.setSoTimeout(2000);
//设置socket发包缓冲为32k;
socket.setSendBufferSize(32*1024);
//设置socket底层接收缓冲为32k
socket.setReceiveBufferSize(32*1024);
//关闭Nagle算法.立即发包
socket.setTcpNoDelay(true);
//连接服务器
socket.connect(endpoint);
//获取输出输入流
out = socket.getOutputStream();
in = socket.getInputStream();
//输出请求
out.write(datas);
out.flush();
//接收应答
BufferedReader br = new BufferedReader( new InputStreamReader(in) , 4096);
StringWriter received = new StringWriter(4096);
char[] charBuf = new char[4096];
int size = 0;
char lastChar = 0;
do {
size = br.read(charBuf , 0 , 4096);
lastChar = charBuf[size-1];
if(lastChar == 0){
received.write(charBuf, 0, size - 1);
}
//System.out.println(received.toString());
}while(lastChar != 0);

return received.toString();

} finally {
if (out != null) {
try {
out.close();
} catch(Exception ex) {
ex.printStackTrace();
}
}
if (in != null) {
try {
in.close();
} catch(Exception ex) {
ex.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
}

public static void main(String[] args) {
byte[] charBuf = new byte[4096];

try {
sendSynMsg("132.97.101.22:7001",charBuf);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}

请问下,传参数 sendSynMsg("132.97.10.55:7001",charBuf);第二个参数该怎么传呢??
...全文
2196 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
a21768541 2010-05-18
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 dr_lou 的回复:]
byte[] charBuf = "cdsn".getBytes();
如果有中文
byte[] charBuf = "cdsn".getBytes("UTF-8");
[/Quote]
cdsn 这个是要传过去的数据?还是什么呢??
dr_lou 2010-05-18
  • 打赏
  • 举报
回复
byte[] charBuf = "cdsn".getBytes();
如果有中文
byte[] charBuf = "cdsn".getBytes("UTF-8");
  • 打赏
  • 举报
回复
//输出请求
out.write(datas);

你自己不是写着注释么?就是将这个数据往 Socket 里面写。
a21768541 2010-05-18
  • 打赏
  • 举报
回复
...没人用socket么??

62,612

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧