⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 server.java

📁 一个小的聊天程序
💻 JAVA
字号:
package talk.npt;

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import java.net.*;

class Server {
    private ServerSocket s;
    private java.util.List svrSocketArrayList;
    private java.util.List outArrayList;
    private SimpleTalk.OutputActionListener listener;
    private ActionListener l;
    private String name = "过客";
    
    public Server(ActionListener listener){
    	svrSocketArrayList = new ArrayList();
    	outArrayList = new ArrayList();
        this.listener = (SimpleTalk.OutputActionListener) listener;
	new StartAndListen().start();
    }
    
    class StartAndListen extends Thread {
    	public void run(){
    	    startServer();
    	}
    	
    	private void startServer(){
            try {
            	s = new ServerSocket(8088);
                while(true){
                    // Blocks until a connection occurs:
                    try {
                        Socket svrSocket = s.accept();
                        svrSocketArrayList.add(svrSocket);
                        l.actionPerformed(
                            new ActionEvent(Server.this,
    			ActionEvent.ACTION_PERFORMED, null));
                        BufferedReader in =
                            new BufferedReader(
                            new InputStreamReader(
                            svrSocket.getInputStream()));
                        // Output is automatically flushed
                        // by PrintWriter:
                        PrintWriter out =
                            new PrintWriter(
                            new BufferedWriter(
                            new OutputStreamWriter(
                            svrSocket.getOutputStream())),true);
                        outArrayList.add(out);
            	        new ListeningInput(svrSocket, in, out).start();
                    } catch(IOException e){
                    	if(e instanceof SocketException ){
                            listener.setInputMsg("Server closed, run as a client.\n");
                            listener.actionPerformed(
                    	        new ActionEvent(Server.this,
    			        ActionEvent.ACTION_PERFORMED, null));
    			    break;
    			 }
    			 else
                	    e.printStackTrace();
                    }
                }
            }catch(IOException e){
            	    e.printStackTrace();
                    listener.setInputMsg("server start failed, you have already started a server!\n");
                    listener.actionPerformed(
                    	new ActionEvent(Server.this,
    			ActionEvent.ACTION_PERFORMED, null));
            }
        }
    }
    
    class ListeningInput extends Thread {
    	private Socket svrSocket;
        private BufferedReader in;
        private PrintWriter out;
    	public ListeningInput(Socket svrSocket, BufferedReader in, PrintWriter out){
    	    this.svrSocket = svrSocket;
    	    this.out = out;
    	    this.in = in;
    	}
    	public void run(){
    	    try{
		listen();
            } catch(IOException e) {
            	e.printStackTrace();
            	listener.setInputMsg("Connection closed.\n");
                listener.actionPerformed(
                	new ActionEvent(Server.this,
			ActionEvent.ACTION_PERFORMED, null));
            }
	}
	private void listen() throws IOException{
    	    try{
    		while(true){
                    String str_out= new String();
                    String sin;
                    while((sin=in.readLine()).length() != 0 )
                    //while((sin=in.readLine()) != null ){
                        str_out += sin + "\n";
                    listener.setInputMsg( str_out);
                    listener.actionPerformed(
                	new ActionEvent(Server.this,
			ActionEvent.ACTION_PERFORMED, null));
		    forwardMessage(out ,  str_out );
    		}
    		
            } finally {
                listener.setInputMsg("Socket closed.\n");
                listener.actionPerformed(
                    new ActionEvent(Server.this,
		    ActionEvent.ACTION_PERFORMED, null));
		closeConnection(svrSocket);
            }
        }
    }
    
    public void addActionListener(ActionListener l){
    	this.l = l;
    }
        
    public void forwardMessage(PrintWriter out, String msg){
        for(Iterator e = outArrayList.iterator();e.hasNext(); ){
            Object o = e.next();
            if(out != o)
	        ((PrintWriter)o).println( msg );
	}
    }
    
    public void sendMessage(String msg){
        for(Iterator e = outArrayList.iterator();e.hasNext(); )
	    ((PrintWriter)e.next()).println( name + ": " + msg + "\n" );
    }
    
    private void closeConnection(Socket svrSocket) throws IOException{
    	svrSocket.close();
    	svrSocketArrayList.remove(svrSocketArrayList.indexOf(svrSocket));
    }
    
    public void closeServer() throws IOException{
        s.close();
        for(Iterator e = svrSocketArrayList.iterator();e.hasNext(); )
	    ((Socket)e.next()).close();
    }
    
    public void setName(String name){
    	if(name != "")
    	    this.name = name;
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -