服务器类代码:
package chat;
import javaio;
import javanet;
import javautil;
/服务器类/
public class Server {
public List<Socket> socketList = new ArrayList<Socket>();//存放所有连接的客户端的集合
public ServerSocket server;//服务器
public int portNum;//端口号
public Server(int portNum){
thisportNum = portNum;
}
public void innit(){
try {
server = new ServerSocket(portNum);
Systemoutprintln("服务器开启成功!");
int socketNum = 0;
while(true){
Socket socket = serveraccept();//被动等待客户端的连接
socketNum++;
Systemoutprintln("第"+socketNum+"个客户端连接成功!!");
socketListadd(socket);//连接的客户端存放到集合里面
new RWThread(socket)start();
}
} catch (IOException e) {
eprintStackTrace();
}
}
class RWThread extends Thread{//接收和发送消息的线程
public Socket socket;
public RWThread(Socket socket){
thissocket = socket;
}
public void run() {
superrun();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(socketgetInputStream()));
while(true){
String message = brreadLine();
Systemoutprintln(message);//接收客户端发来的消息
for(int i=0;i<socketListsize();i++){//发送给所有连接的客户端
PrintWriter pw = new PrintWriter(new OutputStreamWriter(socketListget(i)getOutputStream()));
pwprintln(message);
pwflush();
}
}
} catch (IOException e) {
eprintStackTrace();
}
}
}
public static void main(String[] args) {
int portNum = 8888;//创建服务器的端口号
Server server = new Server(portNum);
serverinnit();
}
}
客户端类:
package chat;
import javaio;
import javanet;
import javautil;
/客户端类/
public class Client {
public Socket socket;
public Client(){
Scanner sca = new Scanner(Systemin);
try {
socket = new Socket("127001",8888);//创建客户端
new ReadThread(socket)start();//开启读取从服务器端发来的信息
while(true){
PrintWriter pw = new PrintWriter(new OutputStreamWriter(socketgetOutputStream()));
String message = scanextLine();
pwprintln(message);//向服务器发送信息
pwflush();
}
} catch (UnknownHostException e) {
eprintStackTrace();
} catch (IOException e) {
eprintStackTrace();
Systemoutprintln("错误:服务器未开启!!!");
}
}
class ReadThread extends Thread{//读取服务器发来信息的线程
public Socket socket;
public ReadThread(Socket socket){
thissocket = socket;
}
public void run() {
superrun();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(socketgetInputStream()));
while(true){
String message = brreadLine();
Systemoutprintln(message);//输出信息
}
} catch (IOException e) {
eprintStackTrace();
}
}
}
public static void main(String[] args) {
Client client = new Client();
}
}
现打开服务器类,然后可以打开多个客户端进行聊天
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)