Java Socket 长连接怎么实现
我想 服务端 发送给客户端 怎么弄 ,短连接只能一次发送 。怎么样可以长期连接 希望提供 服务端 和客户端的 源码 Java 赏分+++
06bqy@163.com
现编这个就是个多线程服务器,只念明要在client不释放连接,服漏高判务器端的run里边写while(TRUE)循环,那么就可以长期连接。
class ConnectionThread extends Thread{
Socket client;
int counter;
public ConnectionThread(Socket cl,int c){
client = cl;
counter= c;
}
@Override
public void run()
{
try{
String destIP=client.getInetAddress().toString();
int destport =client.getPort();
PrintStream outstream=new PrintStream(client.getOutputStream());
DataInputStream instream=new DataInputStream(client.getInputStream());
String inline=instream.readLine();
}/返改/try
catch(IOException e){System.out.println(e);}
}//run
不关闭socket不关渗兄亏闭流 即可
服务端
。。。。
InputStream in = this.socket.getInputStream();
byte[] by = new byte[in.available()];
in.read(by);
for (byte b : by) {
System.out.print(b);
}
byte[] bs = { 11, 22, 33,44 };
OutputStream out = this.socket.getOutputStream();
out.write(bs);
out.flush();
// out.close();
。。。尘悉
客户端在发送时候丛神一样不关闭socket和流就可以了
现编这个就是个多线程服务器,只念明要在client不释放连接,服漏高判务器端的run里边写while(TRUE)循环,那么就可以长期连接。
class ConnectionThread extends Thread{
Socket client;
int counter;
public ConnectionThread(Socket cl,int c){
client = cl;
counter= c;
}
@Override
public void run()
{
try{
String destIP=client.getInetAddress().toString();
int destport =client.getPort();
PrintStream outstream=new PrintStream(client.getOutputStream());
DataInputStream instream=new DataInputStream(client.getInputStream());
String inline=instream.readLine();
}/返改/try
catch(IOException e){System.out.println(e);}
}//run