概述
最近做了一个测试,写了一个简单的socket长连接的测试例子,下面是代码
SocketServer.java
package socket;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket=new ServerSocket(1111);
Socket socket=serverSocket.accept();
while(true){//保持长连接
try {
Thread.sleep(3000);//等待时间
} catch (InterruptedException e1) {
e1.printStackTrace();
}
if (socket !=null){
InputStream is = null;
OutputStream os = null;
try {
String ip = socket.getInetAddress().toString().replace("/", "");
System.out.println("====socket.getInetAddress()====="+ip);
socket.setKeepAlive(true);
is = socket.getInputStream();
os = socket.getOutputStream();
System.out.println("服务器端接受请求");
byte[] buff = new byte[5];
is.read(buff);
String tempdata =new String(buff); // StreamEazyUse.getContent(is);
if (tempdata.equals("quit1")) {
System.out.println("不处理,继续::"+tempdata);
continue;
}
System.out.println("接收到的数据为:"+tempdata);
os.write("world".getBytes());
os.flush(); //发送响应
// is.close();
// os.close();
}catch(Exception e){
System.out.println("出现了错误,关闭连接");
if (is!= null)
is.close();
if (os!= null)
os.close();
e.printStackTrace();
}
}
}
}
}
SocketClient:
package socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class SocketClient {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket socket = new Socket("localhost",1111);
if (socket.isConnected()){
OutputStream os =null;
InputStream is = null;
while (true) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String in = br.readLine();
os = socket.getOutputStream();
os.write(in.getBytes());//"hello".getBytes());
os.flush();
is = socket.getInputStream();
byte[] resp = new byte[5];
is.read(resp);
System.out.println("response:" + new String(resp));
} catch (Exception e) {
e.printStackTrace();
if(os != null)
os.close(); //由于是长连接,抛异常时要关闭os,否则会broken pipe
if(is != null)
is.close();
} finally {
System.out.println("do nothing");
}
}
}
}
}
最后
以上就是淡然钢笔为你收集整理的socket长连接例子(server&client)的全部内容,希望文章能够帮你解决socket长连接例子(server&client)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复