关于java socket长连接问题 求客户端和服务器源代码及解释 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 长连接,只要你不关闭服务端,就不会关闭,不管你有多少客户端都没有问题。package lmd.echo.socket.server;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.ServerSocket;import java.net.Socket;import org.apache.log4j.Logger;/** * * @author:牛车水 * @mail:[email protected] * @date:20090924 * @info:java socket 服务端 * */public class SocketServer implements Runnable{ private Socket client; private ServerSocket server; public SocketServer() { // TODO Auto-generated constructor stub } Logger logger = Logger.getLogger(SocketServer.class); public void run(){ logger.info("java socket 开始执行……"); try { server = new ServerSocket(8888); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try{ while(true){ String firstValue = ""; String returnStr = ""; client = server.accept(); BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); PrintWriter out = new PrintWriter(client.getOutputStream()); ExecuteSocketServer ess = new ExecuteSocketServer(); String reciverInfo = in.readLine();//得到客户端传来的数据 //your code out.println(returnStr); out.flush(); client.close(); } } catch (IOException ex){ ex.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { } } public static void main(String[] args){ Thread t = new Thread(new SocketServer()); t.start(); }} 长:connect连上后不断开, 进行N次收发操作. 长连接: run(){ while(NotEnd){ read process write } } 下面是我从网上找的,但是有人说java的ss.setKeepAlive(true);方法很迟钝,有更好的解释吗? 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(); } } 谁能解释下面的这段代码在内存里是怎么执行的 线程问题,请高手帮忙! 对静态方法和静态域不太明白,谁能指点一下? java问题,请高手解决 yqj2065(严千钧) 朋友来领个分,谢谢。 如何在目录树上建菜单 请问,用JBuilder8做一个工程,怎样删除你建立的文件呢?? 怎样用JAVAHELP做帮助文档小女 子急用在线等待在此先谢谢了。 byte[] 转换成中文的问题?详情如一! java.sql.SQLException: ORA-00936: 缺失表达式 Java文本框问题? ajax框架,散分啊!!!!!!!
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;import org.apache.log4j.Logger;/**
*
* @author:牛车水
* @mail:[email protected]
* @date:20090924
* @info:java socket 服务端
*
*/
public class SocketServer implements Runnable{ private Socket client;
private ServerSocket server;
public SocketServer() {
// TODO Auto-generated constructor stub
} Logger logger = Logger.getLogger(SocketServer.class);
public void run(){
logger.info("java socket 开始执行……");
try {
server = new ServerSocket(8888);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try{
while(true){
String firstValue = "";
String returnStr = "";
client = server.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter out = new PrintWriter(client.getOutputStream());
ExecuteSocketServer ess = new ExecuteSocketServer();
String reciverInfo = in.readLine();//得到客户端传来的数据
//your code
out.println(returnStr);
out.flush();
client.close();
}
} catch (IOException ex){
ex.printStackTrace();
} catch (Exception e){
e.printStackTrace();
} finally {
} }
public static void main(String[] args){
Thread t = new Thread(new SocketServer());
t.start();
}}
长连接:
run(){
while(NotEnd){
read
process
write
}
}
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();
}
}