`
flowercat
  • 浏览: 358195 次
社区版块
存档分类
最新评论

java socket 长连接发送数据

    博客分类:
  • java
阅读更多
Client:

Socket ss = null;
InputStream in = null;
DataOutputStream dos = null;

public MySocketClient() {

}

public static byte[] intToBytes(int v) {
byte[] b = new byte[4];
b[0] = (byte) ((v >>> 24));
b[1] = (byte) ((v >>> 16));
b[2] = (byte) ((v >>>);
b[3] = (byte) ((v >>> 0));
for(int i=0;i<b.length;i++)
System.out.println(b[i]);
System.out.println(Integer.toBinaryString(v));
return b;
}

public static int bytesToInt(byte[] b) {
int ret = 0;
        ret |= (b[0] & 0xff) << 24;
        ret |= (b[1] & 0xff) << 16;
        ret |= (b[2] & 0xff) << 8;
        ret |= (b[3] & 0xff) << 0;
        return ret;
}

public boolean keeplive() {
try {
if (ss == null || !(ss.isConnected() && !ss.isClosed())) {
ss = new Socket("127.0.0.1", 9901);
                                     ss.setKeepAlive(true);
in = ss.getInputStream();
dos = new DataOutputStream(ss.getOutputStream());
}
return true;
} catch (IOException e) {
if (ss != null) {
try {
ss.close();
ss = null;
dos = null;
in = null;
} catch (IOException e1) {
}
}
try {
Thread.sleep(1000 * 5);
} catch (InterruptedException e1) {
}
return false;
}
}

public void run() {
while (!keeplive())
;
while (true) {
try {
byte[] b = "hello".getBytes();
int l = b.length;
dos.write(intToBytes(l));
dos.write(b);
dos.flush();

int leng = 0;
byte[] buffer = new byte[1024];
leng = in.read(buffer);
if (leng > 0)
System.out.println(new String(buffer));
Thread.sleep(1000);
} catch (Exception e) {
if (ss != null) {
try {
ss.close();
ss = null;
dos = null;
in = null;
} catch (IOException e1) {
e1.printStackTrace();
}
}
while (!keeplive())
;
}
}
}





Server:


public void run() {

try {
while (true) {
byte[] totalData = new byte[0];
int totalLeg = 0;
int leng = 0;

byte[] size = new byte[4];
int readsize = 0;
if (in.read(size) > 0)
readsize = bytesToInt(size);
else
continue;

byte[] buffer = new byte[readsize];
leng = in.read(buffer, 0, readsize);
System.out.println(new String(buffer).trim());
int le=(int)(Math.random()*100)+1;
byte[] b=new byte[le];
new Random().nextBytes(b);
os.write(b);
os.flush();
}
} catch (IOException e) {
// e.printStackTrace();
}
finally {
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}



public static void main(String[] args) throws IOException{
ServerSocket ss=null;
try {
ss=new ServerSocket(9901);
} catch (IOException e) {
e.printStackTrace();
}
while(true){
Socket socket=ss.accept();
socket.setKeepAlive(true);
new MyRunableSocket(socket).start();
}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics