java socket 长连接发送数据概要

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(); 

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值