Socket编程
Socket的英文原义是“孔”或“插座”。
Socket类(套接字)可以看成是两个网络应用程序进行通信时,各自通信连接中的端点。当然,Socket也可以提供多个端口的连接服务
数据传输其实就是客户端到服务端,服务端到客户端的一个过程,数据是以流的形式进行传输的
特点:基于TCP连接,更安全所以适合应用于即时通讯
流程: 以客户端(client)及服务端(server)为例
- server运行开始监听
- client运行发出请求
- 建立连接开始通讯
以聊天功能为例
- 客户端代码
public class Client {
public static void main(String[] args) {
Socket socket = null;
OutputStream os = null;
OutputStreamWriter osw = null;
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
try {
while (true) {
// 创建客户端对象,设置发送的地址及端口号
socket = new Socket("172.16.4.127", 5555);
// 从控制台获取要发送的内容
Scanner scan = new Scanner(System.in);
String sendContent = scan.nextLine();
// 将要发送的内容通过输出流的形式进行写的操作
os = socket.getOutputStream();
// 将字节流转为字符流进行写的操作(当中会写字符串)
osw = new OutputStreamWriter(os);
// 进行写的操作
osw.write(sendContent);
// 刷新流
osw.flush();
// 告诉服务器写完了,请求接收
socket.shutdownOutput();
// 以下为获取服务端的反馈
// 从socket中获取输入流对象
is = socket.getInputStream();
// 从字节流转为字符流进行读取
isr = new InputStreamReader(is);
// 使用字符缓冲流进行读取操作
br = new BufferedReader(isr);
String getContent = null;
while ((getContent = br.readLine()) != null) {
System.out.println(getContent);
}
// 结束判断
if (sendContent.equals("Over!")) {
break;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
if (isr != null) {
isr.close();
}
if (is != null) {
is.close();
}
if (osw != null) {
osw.close();
}
if (os != null) {
os.close();
}
if (socket != null) {
socket.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
- 服务端
public class Server {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
OutputStream os = null;
OutputStreamWriter osw = null;
try {
// 1.创建服务端的Socket对象
serverSocket = new ServerSocket(5555);
while (true) {
// 2.监听对应端口号下的所有应用
socket = serverSocket.accept();
// 3.获取客户端发送过来的消息
is = socket.getInputStream();
// 3.1将字节流转换为字符流进行读操作
isr = new InputStreamReader(is);
// 3.2使用字符缓冲流处理读取重复的问题
br = new BufferedReader(isr);
String readContent = null;
while ((readContent = br.readLine()) != null) {
System.out.println(readContent);
}
// 给客户端返回信息
// 4.1 从Socket中获取输出流
os = socket.getOutputStream();
// 4.2 将字节输出流转换为字符输出流
osw = new OutputStreamWriter(os);
Scanner scan = new Scanner(System.in);
String rebackContent = scan.nextLine();
osw.write(rebackContent);
osw.flush();
socket.shutdownOutput();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (osw != null) {
osw.close();
}
if (os != null) {
os.close();
}
if (br != null) {
br.close();
}
if (isr != null) {
isr.close();
}
if (is != null) {
is.close();
}
if (socket != null) {
socket.close();
}
if (serverSocket != null) {
serverSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
结果