Socket介绍
Socket简介
Socket又称”套接字”,应用程序通常通过”套接字”向网络发出请求或者应答网络请求。ServerSocket用于服务器端,Socket是建立网络连接时使用的。在连接成功时,应用程序两端都会产生一个Socket实例,操作这个实例,完成所需的会话。对于一个网络连接来说,套接字是平等的,并没有差别,不因为在服务器端或在客户端而产生不同级别。包含了网络通信所需要的五种基本信息:通信协议、本地协议地址、本地主机端口、远端主机地址和远端协议端口。
Socket通信模型
实现的功能
(1)实现了服务器和客户端之间的连接通信
(2)实现了客户端与客户端之间的连接通信
实现过程
(1)首先服务器启动,启动多线程,创建ServerSocket,等待客户端的链接
(2)启动客户端,创建一个socket并请求和服务器创建连接
(3)服务器接受客户端的请求,启动一个线程负责监听客户端的对话请求,并将改请求存在List中。
(4)服务器接受请求后,客户端启动线程监听来自服务器的消息
(5)按照协议进行通信
(6)关闭Socket
当服务器接受到已经建立连接的客户端请求时,将客户端的请求内容通过遍历List来发送给各个客户端,从而实现客户端和客户端之间的连接。
代码实现
- ChatClient:客户端类
- ChatServer:服务器类
ChatServer.java
package cn.newtol;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
/**
* @Author: REN
* @Description:
* @Date: Created in 20:44 2018/5/29
*/
public class ChatServer {
private boolean started = false;
private List<ChatThread> chatThreads = new ArrayList<ChatThread>();
public static void main(String[] args) {
new ChatServer().startServer();
}
private void startServer(){
try {
//开启服务端Socket
ServerSocket serverSocket = new ServerSocket(8888);
started = true;
while(started){
//接受客户端连接请求
Socket socket = serverSocket.accept();
System.out.println("一个客户端已连接");
//开启线程处理客户端通信
ChatThread chatThread = new ChatThread(socket);
chatThreads.add(chatThread);
new Thread(chatThread).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private class ChatThread implements Runnable{
private Socket socket;
private DataInputStream dataInputStream =null;
private DataOutputStream dataOutputStream =null;
private boolean isConnected = false;
OutputStream outputStream =null;
PrintWriter printWriter =null;
public ChatThread(Socket socket) {
super();
this.socket = socket;
}
//发送信息
private void send(String strMsgIn){
try{
dataOutputStream.writeUTF(strMsgIn);
dataOutputStream.flush();
}catch(IOException e){
e.printStackTrace();
}
}
@Override
public void run() {
try{
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
//读取数据
isConnected = true;
while(isConnected){
String strMsgIn= dataInputStream.readUTF();
System.out.println(strMsgIn);
//接收到数据后发送给每个客户端
for(int i =0;i<chatThreads.size();i++){
chatThreads.get(i).send(strMsgIn);
}
}
}catch (IOException e) {
try {
//如果客户端出错或关闭,直接关闭连接,并移除List中的当前线程
socket.close();
chatThreads.remove(this);
} catch (IOException e1) {
e1.printStackTrace();
}
} finally{
try {
dataInputStream.close();
dataOutputStream.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
ChatServer.java
package cn.newtol;
/**
* @Author: REN
* @Description:
* @Date: Created in 20:42 2018/5/29
*/
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
@SuppressWarnings("serial")
public class ChatClient extends Frame {
private TextArea textArea = new TextArea();
private TextField textField = new TextField();
private DataOutputStream dataOutputStream = null;
private DataInputStream dataInputStream = null;
private Socket socket = null;
private boolean isConnected = false;
private Thread thread=null;
public static void main(String[] args) {
new ChatClient().frameClient();
}
//聊天窗口
public void frameClient(){
setSize(400, 400);
setLocation(400,300);
add(textArea,BorderLayout.NORTH);
add(textField,BorderLayout.SOUTH);
pack();
textField.addActionListener(new TfListener());
//关闭窗口事件监听
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
disconnected();
System.exit(0);
}
});
this.connect();
setVisible(true);
}
//链接服务器地址
private void connect(){
try {
socket = new Socket("127.0.0.1", 8888);
thread=new Thread(new ChatThread());
thread.start();
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//断开连接
private void disconnected(){
isConnected = false;
try {
dataOutputStream.close();
dataInputStream.close();
socket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
//键盘回车事件
private class TfListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
String strMsg = textField.getText();
textField.setText("");
try {
dataOutputStream.writeUTF(strMsg);
dataOutputStream.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
//开启线程接受服务器信息
private class ChatThread implements Runnable{
@Override
public void run() {
try {
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
isConnected = true;
while(isConnected){
String msg= dataInputStream.readUTF();
String taText = textArea.getText();
textArea.setText(taText+msg+"
");
}
}catch (SocketException e) {
System.out.println("客户端退出");;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
运行方法
先启动服务器类,然后连续启动多个客户端类,在弹出的操作窗口中进行消息的发送即可。
源码下载地址
参考文献:
菜鸟教程【Android 基础入门教程】.博客地址:http://www.runoob.com/w3cnote/android-tutorial-socket1.html