www.pudn.com > ServerClientjava写的简单聊天程序.rar > Client.java


/* 
 * Created on 2004-12-9 
 * 
 * To change the template for this generated file go to 
 * Window>Preferences>Java>Code Generation>Code and Comments 
 */ 
 
/** 
 * @author Administrator 
 * 
 * To change the template for this generated type comment go to 
 * Window>Preferences>Java>Code Generation>Code and Comments 
 */ 
import java.io.*; 
import java.net.*; 
public class Client { 
	 
	public static void main(String[] args) throws IOException{ 
	Socket socket=null; 
//由Socket对象得到输出流,并构造PrintWriter对象 
	PrintWriter os=null; 
	BufferedReader is=null; 
	boolean runable=true; 
	String toServer; 
	try{ 
		socket=new Socket("127.0.0.1",4000); 
		os=new PrintWriter(socket.getOutputStream(),true); 
		is=new BufferedReader(new InputStreamReader(socket.getInputStream()));	 
	}catch(UnknownHostException e){ 
		System.err.println("Can not find Server !"); 
		System.exit(1); 
	}catch(IOException e){ 
		System.err.println("Can not get the Reader and Writer of Socket"); 
		System.exit(1); 
	} 
	BufferedReader stdIn=new BufferedReader(new InputStreamReader(System.in)); 
	os.println("您好,我是新用户"); 
	ReceiveServerThread readServerThread=new ReceiveServerThread(is); 
	readServerThread.start(); 
	while(runable) 
	{ 
		toServer=stdIn.readLine(); 
		os.println(toServer); 
		if(toServer.equals("bye")) break; 
		runable=readServerThread.runable; 
	} 
	readServerThread.fromServer="Welcome come again !"; 
	readServerThread.runable=false; 
	os.close(); 
	is.close(); 
	stdIn.close(); 
	socket.close(); 
	} 
} 
class ReceiveServerThread extends Thread 
{ 
	BufferedReader in=null; 
	String fromServer=""; 
	boolean runable=true; 
	public ReceiveServerThread(BufferedReader in) 
	{ 
		this.in=in; 
	} 
	public void run() 
	{ 
		while(runable) 
		{ 
			try 
			{ 
				fromServer=in.readLine(); 
			} 
			catch(Exception e) 
			{ 
				runable=false; 
			} 
			if(fromServer.equals("bye")) 
			{ 
				System.out.println("Server exit"); 
				runable=false; 
				break; 
			} 
			System.out.println("服务器说: "+fromServer); 
		} 
	} 
}