package cn.wang;
import java.io.*;
import .*;
public class Server {
static int num = 1;//客户端计数
public static void main(String[] args) {
// TODO Auto-generated method stub
ServerSocket server = null;
Socket client = null;
while(true) {
try {
server = new ServerSocket(4444);
//绑定端口,监听客户端
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Error:"+e);
}
try {
client = server.accept();
//与客户端建立连接
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("接受请求失败!");
System.exit(-1);
}
System.out.println("Client["+Server.num+"]登录...");
ServerThread st = new ServerThread(client);
Thread t= new Thread(st);
//监听到客户端,为他创建线程,主程序返回继续监听
t.start();
try {
server.close();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("关闭失败!");
}
num++;
}
}
public static class ServerThread implements Runnable{
private Socket client;
public ServerThread(Socket client) {
this.client = client;
}
public void run() {
try {
BufferedReader is = new BufferedReader(new InputStreamReader(client.getInputStream()));
//将从客户端接受的信息存放到缓存is中
PrintWriter os = new PrintWriter(client.getOutputStream());
//从socket获取客户端的输出流,通过os向客户端发送消息
BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
//建立缓存,为后面输入数据做准备
System.out.println("Client:"+is.readLine());
//打印客户端发来的信息
String inputString = sin.readLine();
//从键盘输入信息,存放在inputString中
while(inputString!=null&&inputString.trim().equals("quit")){
os.println(inputString);
//os.println向客户端发送消息,内容是inputString
os.flush();
//刷新输出流,使client马上得到该信息
System.out.println("Server发送的信息为:"+inputString);
//打印服务器向客户端发送的信息
System.out.println("Client发来的信息为:"+is.readLine());
//打印客户端发来的信息
inputString = sin.readLine();
//继续读入数据
}
os.close();//关闭Socket输出流
is.close();//关闭Socket输入流
client.close();//关闭Socket
System.out.println("通信结束!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
如果觉得《java socket 通信协议_java网络通信(基于TCP协议可靠通信的socket编程)》对你有帮助,请点赞、收藏,并留下你的观点哦!