client.java

来自「一个小的聊天程序」· Java 代码 · 共 94 行

JAVA
94
字号
package talk.npt;

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

class Client {
    private Socket cltSocket;
    private PrintWriter out;
    private BufferedReader in;
    private InetAddress addr;
    private int port;
    private String ipAddress;
    private SimpleTalk.OutputActionListener listener;
    private String name = "过客";
    
    
    public Client(String ipAddress, int port, ActionListener listener){
    	this.ipAddress = ipAddress;
    	this.port = port;
    	this.listener = (SimpleTalk.OutputActionListener) listener;
    }
    
    public void connect(){
        try {
    	    addr = InetAddress.getByName(ipAddress);
	    cltSocket = new Socket(addr, port);
            //outputArea.append("Connection setup!\n");
            in =
                new BufferedReader(
                new InputStreamReader(
                cltSocket.getInputStream()));
            // Output is automatically flushed
            // by PrintWriter:
            out =
                new PrintWriter(
                new BufferedWriter(
                new OutputStreamWriter(
                cltSocket.getOutputStream())),true);
            new ListeningInput().start();
        } catch(Exception ex) {
                ex.printStackTrace();
        }
    }
    
    class ListeningInput extends Thread {
    	public void run(){
    	    try{
		listen();
            } catch(IOException e) {
            	listener.setInputMsg("Connection closed.\n");
                listener.actionPerformed(
                	new ActionEvent(Client.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(Client.this,
			ActionEvent.ACTION_PERFORMED, null));
    		}
            } finally {
                listener.setInputMsg("Socket closed.\n");
                listener.actionPerformed(
                    new ActionEvent(Client.this,
		    ActionEvent.ACTION_PERFORMED, null));
		closeConnection();
            }
        }
    }
    
    public void sendMessage(String msg){
        out.println( name + ": " + msg + "\n" );
    }
    
    public void closeConnection() throws IOException {
    	cltSocket.close();
    }
    
    public void setName(String name){
    	if(name != "")
    	    this.name = name;
    }
}

⌨️ 快捷键说明

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