Socket网络通信实战
2017-08-31 本文已影响0人
kjy_112233
- Socket聊天服务器任务:ChatServer类负责开启Server端服务;ReceiveMsg负责接收消息;SendMsg负责发送消息;Server端响应请求,向Client端返回数据。
public class ChatServer extends Thread {
private ChatServer() throws IOException {
//创建Socket服务
CreateSocket();
}
public void run() {
Socket client;
//定义接收的文本
String txt;
try {
//始终在监听
while (true) {
//开启线程实时监听socket端口
//获取应答消息
client = ResponseSocket();
//响应客户端连接请求
while (true) {
//接受客户端消息
txt = ReceiveMsg(client);
//连接获得客户端发来消息
//并将其显示在Server端屏幕上
SendMsg(client, txt);
//向客户端返回消息
if (true) {
break;
}
//中断,继续等待连接请求
}
//关闭此次连接
CloseSocket(client);
}
} catch (IOException e) {
e.printStackTrace();
}
}
//定义一个ServerSocket对象
private ServerSocket server = null;
//定义端口
private static final int PORT = 5000;
//定义写buffer
private BufferedWriter writer;
//定义读buffer
private BufferedReader reader;
//实例化ServerSocket
private void CreateSocket() throws IOException {
server = new ServerSocket(PORT, 100);
}
//接收消息
private Socket ResponseSocket() throws IOException {
Socket client = server.accept();
return client;
}
//关闭打开的连接和缓存
private void CloseSocket(Socket socket) throws IOException {
reader.close();
writer.close();
socket.close();
}
//封装发送消息的方法
private void SendMsg(Socket socket, String Msg) throws IOException {
//要发送的消息写入BufferedWriter中
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
//添加空行分隔符
writer.write(Msg + "\n");
//刷新,发送
writer.flush();
}
//接收消息的方法
private String ReceiveMsg(Socket socket) throws IOException {
//保存到读buffer
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//将接收到的信息保存到字符串中
String txt = "Server send:" + reader.readLine();
return txt;
}
}
启动服务器的代码如下
ChatServer chatServer = null;
try {
chatServer = new ChatServer();
} catch (IOException e) {
e.printStackTrace();
}
//检测服务器是否已经起动,如果没有则启动服务器
if(chatServer != null){
chatServer.start();
}
客户端的任务:客户端发起连接请求,并向服务器发送数据;客户端接收服务器的数据。
//客户端获取消息类
private Socket RequestSocket(String host, int port) throws UnknownHostException, IOException {
Socket socket = new Socket(host, port);
return socket;
}
//客户端发送消息类
private void SendMsg(Socket socket, String msg) throws IOException {
//要发送的消息写入BufferedWriter中
BufferedWriter wirter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
//格式转换
wirter.write(msg.replace("\n", " ") + "\n");
//刷新,发送
wirter.flush();
}
//客户端接收消息类
private String ReceiveMsg(Socket socket) throws IOException {
//写入读buffer
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//将信息保存到字符串中
String txt = reader.readLine();
return txt;
}