connection.java

来自「一个很好的JAVA聊天室系统 可以在课堂里实践并且进行聊天」· Java 代码 · 共 75 行

JAVA
75
字号
import java.awt.*;
import java.net.*;
import java.io.*;
import java.util.*;
import FIFO;


class Connection extends Thread {
  static int numberOfConnections = 0;
  protected Socket client;
  protected ConnectionWatcher watcher;
//  protected DataInputStream in;
  protected PrintStream out;
  protected ServerWriter writer;
  BufferedReader reader;

  public Connection (Socket client_socket, ThreadGroup CurrentConnections,
           int priority, ConnectionWatcher watcher, ServerWriter writer) {
     super(CurrentConnections,"Connection number"+numberOfConnections++);
     this.setPriority(priority);
     
     client = client_socket;
     this.watcher = watcher;
     this.writer = writer;

     try {
          InputStream is = client.getInputStream();
          reader=new BufferedReader(new InputStreamReader(is));
//          in = new DataInputStream(client.getInputStream());
          out = new PrintStream(client.getOutputStream());
          writer.OutputStreams.addElement(out);  // store object out in a vector    
         }
     catch (IOException e) {
          try {client.close();}
          catch (IOException e2) {};
          System.err.println(" Exception while getting socket stream: "+e);
          return;
         }
      this.start();
  }  // end of constructor

  public void run() {
      String inline;
      out.println(" Welcome to our internet Chat!");  
      try {
	   while(true)
              {
                inline = reader.readLine();
                if (inline == null) break;
                writer.outdata.push(inline);  // store data in FIFO              
                synchronized(writer) { writer.notify();} // wake up writer
              }
     	   }
       catch (IOException e) {}
       finally {
                try { client.close();}
                catch (IOException e2) {};
                synchronized(watcher) { watcher.notify(); }
               }
  } // end of run()

  public String getInfo() {
	String inline = "";
        try { inline = reader.readLine();}
        catch (IOException e)
           { System.out.println(" Caught an exception: "+e); }

        writer.outdata.push(inline + " has joined this chat!");  
        synchronized(writer) { writer.notify();}
        return (inline + " connected from: "
              + client.getInetAddress().getHostName());  
  }

}         

⌨️ 快捷键说明

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