首先让我们看看最简单的socket client与server实例:
Client端程序:
public class MyClient {
public static void main(String[] args) {
ObjectOutputStream oos = null;
ByteArrayOutputStream bos = null;
Socket client = null;
try {
People p = new People(“2″,”yangyu”,”4″,”5″,”6″);
oos = new ObjectOutputStream(bos = new ByteArrayOutputStream()); //初始化object输出流
oos.writeObject(p); //将People对象写入输出流
byte[] bytes = bos.toByteArray(); //获取People对象的byte数组(也就是序列化People)
client = new Socket(“127.0.0.1”,20007); //连接127.0.0.1的20007端口
client.setSoTimeout(10000); //设置超时时间
client.getOutputStream().write(bytes); //向server发送byte[]数组
byte[] bytes1 = IOUtils.readFully(client.getInputStream(),18,false); //获取server返回数据
System.out.println(new String(bytes1));
System.out.println(bytes1.length);
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
oos.close();
bos.close();
System.out.println(client.isClosed());
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Server端程序:
public class MyServer {
public static void main(String[] args) {
ServerSocket server = null;
Socket client = null;
ObjectInputStream ois = null;
ByteArrayInputStream bis = null;
try {
server = new ServerSocket(20007); //启动Socket server,监听20007端口
client = server.accept(); //阻塞并等待接收客户端发送数据并生成client
byte[] bytes = IOUtils.readFully(client.getInputStream(),-1,false);//获取客户端发送过来的数据
bis = new ByteArrayInputStream(bytes);
ois = new ObjectInputStream(bis);
People people = (People) ois.readObject();//反序列化
System.out.println(“people name:”+people.getName());
String res = “消息已经收到”;
client.getOutputStream().write(res.getBytes());//向客户端发送数据
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
bis.close();
ois.close();
client.close();
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
以上一个Client和一个Server,最简单的例子,但是体现socket编程。
如果需要Server服务端一直监听端口,那么只需要循环就可以(server.accept()会阻塞等待请求),至于需要高并发的响应,那么Server对数据业务的处理交由线程池来做吧。
转载请注明来源网站:blog.ytso.com谢谢!
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/14775.html