socket长连接,

我想建立socket长连接,建立一个连接可连续发送多次数据。现在遇到的问题是,服务端程序在监听时无法判断客户端传送数据是否完成,如果我在客户端使用socket.shutdownOutput();那么我不能用一个连接连续发送2次数据。如果不使用,这服务端一直在监听,不能进行数据处理。请问我该怎么实现?
贴出部分程序:
客户端:public class SocketClient {
private Socket socket = null;

public void connect() {
try {
if (socket == null) {
socket = new Socket();
socket.setSoTimeout(10000);
socket.setReceiveBufferSize(2048);
socket.setSendBufferSize(2048);
socket.connect(new InetSocketAddress("127.0.0.1", 8081),
10000);
socket.setKeepAlive(true);
}
} catch (Exception e) {
e.printStackTrace();
}
}

public void send(byte[] s) {
try {
InputStream is = new
BufferedInputStream(socket.getInputStream());
OutputStream os = new BufferedOutputStream(socket.getOutputStream());
PrintWriter pw = new PrintWriter(os);
byte[] buf = new byte[1000];
os.write(s);
os.flush();
socket.shutdownOutput();//关键在这个地方,关闭的话无法连续发送,不关闭服务端无法监听客户端是否发送数据结束

} catch (Exception e) {e.printStackTrace();
}finally{}
}

服务端:public class ServerThread extends Thread {
private Socket socket = null;
private int clientNum = 0;

public ServerThread(Socket socket, int clientNum) {
this.socket = socket;
this.clientNum = clientNum + 1;
}
  
public void run() {
try {
BufferedReader bfr = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
OutputStream os = socket.getOutputStream();
String reads = read(socket.getInputStream());
System.out.println(reads);
} catch (Exception e) {
e.printStackTrace();
}
}

private String read(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
while(true) {
int len = is.read(buf, 0, buf.length);
if(len < 0) { break; }
baos.write(buf, 0, len);
}
return baos.toString();
//return baos.toByteArray();
}


import java.net.ServerSocket;
import java.net.Socket;

public class SocketServer {
private static int clientNum = 0;

public static void start() {
try {
ServerSocket server = new ServerSocket(8081);
 
boolean listener = true;
while (listener) {
new ServerThread(server.accept(), clientNum).start();
clientNum++;
}
} catch (Exception e) {
e.printStackTrace();
}
}

public static void main(String args[]) throws Exception {
start();
}
}

阅读更多
想对作者说点什么? 我来说一句

socket长连接demo

2016年07月06日 2.33MB 下载

Socket长连接测试程序

2015年12月23日 40B 下载

没有更多推荐了,返回首页

不良信息举报

socket长连接,

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭