关闭

socket长连接,

标签: socketexceptionbytestringclassthread
741人阅读 评论(1) 收藏 举报

我想建立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();
}
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:9837次
    • 积分:268
    • 等级:
    • 排名:千里之外
    • 原创:15篇
    • 转载:1篇
    • 译文:0篇
    • 评论:4条
    文章存档
    最新评论