📄 ext7_server.java
字号:
import java.io.*;
import java.net.*;
public class Ext7_Server extends Thread
{
static int ServerPort=5000;//服务端口5000
public static int i=0;
public static String[] Count=new String[10];//用来记录客户登陆情况
private Socket Server;
public Ext7_Server()
{
}
//***********************************************************
//运行服务器
//************************************************************
public void run()
{
ServerThread.Show("服务器端程序启动...");
try{
ServerSocket serversocket=new ServerSocket(ServerPort);
while(true)
{
Server=serversocket.accept();
ServerThread ct=new ServerThread(Server);
ct.start();
}
}catch(Exception e){
e.printStackTrace();
ServerThread.Show("服务器端程序关闭。。。");
System.exit(0);
}
}
//*******************************************************
//对用户进行标志
//*******************************************************
public static synchronized void SendMessage(String msg)
{
Count[i]=msg;
i=(i+1)%10;
Count[i]="*";//以“*”为标志
}
public static void main(String[] args)
{
Ext7_Server sp=new Ext7_Server();
sp.start();
}
}
//********************************************************
//服务端核心
//********************************************************
class ServerThread extends Thread
{
private static int ii=0;
private Socket s;
String msg=null;
ServerSocket serverSocket=null;
Socket socket=null;
BufferedReader Min=null;
PrintWriter Mout=null;
public ServerThread(Socket s)
{
this.s=s;
}
public void run()
{
try
{
Min=new BufferedReader(new InputStreamReader(s.getInputStream()));
Mout=new PrintWriter(s.getOutputStream());
SendToAll STA=new SendToAll();
STA.start();
msg=Min.readLine();
ii++;
System.out.println("有人进入了聊天室,现在有"+ii+"个人在聊天");
while(!msg.equals("exit"))
{
Ext7_Server.SendMessage(msg);
msg=Min.readLine();
}
if(msg.equals("exit"))
{
--ii;
System.out.println("有人离开了聊天室,现在有"+ii+"个人在聊天");
Min.close();
Mout.close();
s.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
static void Show(String info)
{
System.out.println(info);
}
class SendToAll extends Thread
{
private int j=-1;
public void run()
{
//cli=new Socket(5001);
while(true)
{
try
{
sleep(500);
if(j==-1)
{
if(!Ext7_Server.Count[0].equals("*"))
{
Mout.println(Ext7_Server.Count[0]);
Mout.flush();
j=1;
}
else
{
Mout.println(Ext7_Server.Count[1]);
Mout.flush();
j=2;
}
}
while(!Ext7_Server.Count[j].equals("*"))
{
Mout.println(Ext7_Server.Count[j]);
Mout.flush();
j=(j+1)%10;
}
}
catch(Exception e)
{
}
}
}
}
}
//}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -