Socket通信简单基本操作
来源:互联网 发布:cf为什么老是网络异常 编辑:程序博客网 时间:2024/06/18 16:45
客户端:
//申明socket
Socket socket=new Socket(host,post)//post是端口,host是服务器IP地址
//获取socket输入流,服务器传回来的数据
BufferedReader in= new BufferedReader(new InputStreamReader(socket.getInputStream()));
//输出流
PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
// 输出到socket连接的另外一端
if (socket.isConnected()) {
if (!socket.isOutputShutdown()) {
out.println(msg);//服务器端和客户端都可以用这个输出消息
}
}
//获取另外一端返回的数据:
if (!socket.isClosed()) {
if (socket.isConnected()) {
if (!socket.isInputShutdown()) {//判断输入通道是否关闭
if ((content = in.readLine()) != null) {
content += "\n";
} else {
}
}
}
}
服务端:或者另外一端
ServerSocket server=new ServerSocket(PORT);//设定端口号的服务套接字
ExecutorService mExecutorService=Executors.newCachedThreadPool();//创建线程池处理接受到的客户端socket
Socket client = null;
while(true) {
client = server.accept();
//把客户端放入客户端集合中
mList.add(client);
mExecutorService.execute(new Service(client)); //start a new thread to handle the connection
}
其余读写操作和客户端大同小异
结论:
socket套接字要一直保持连接,流量和电量消耗大。获取socket携带的数据要在子线程里面操作。
- Socket通信简单基本操作
- 【网络通信】socket,bind等基本操作
- 笔记-Socket通信-基本操作(启动/连接/发送/关闭)
- Socket通信基本流程
- socket通信基本流程
- Socket通信基本流程
- socket<->基本通信
- socket通信基本流程
- socket通信基本流程
- socket通信基本流程
- socket通信基本流程
- Socket通信基本流程
- socket通信基本流程
- 基本的Socket通信
- 简单实现Socket通信
- 简单的SOCKET通信
- c++ 简单SOCKET 通信
- socket通信简单例子
- JavaWeb——Day15_2
- Min Stack -- LeetCode
- Duplicate Symbol链接错的原因总结和解决方法
- 公共函数 data_auth_sign 的用途
- POJ 3304 Segments 枚举线段端点+判断相交
- Socket通信简单基本操作
- 【健康生活】不要放弃你的梦想
- miniz compared to other real-time and high-ratio compressors
- Cisco设备使用Syslog服务器的设置方法
- MySQL Sending data导致查询很慢的问题详细分析
- spring学习10- mvc 异步之servlet异步基础知识
- Linux 指令篇:系统设置--export
- 强大的JQuery表格控件FooTable
- Android中使用代码截图的各种方法总结