//server.java import java.io.*; import sun.net.*; class
server extends NetworkServer //定义服务器类 {DataInputStream net_input; //定义数据输出
PrintStream net_output; //定义数据输入 public static void main(String args[]) { new
server();} public server() //运行服务器功能,并把端口设为1111 { try
{startServer(1111);} catch (Exception e) { System.out.println( "Unable to start
server."); return; } System.out.println("Waiting for clients..."); } public
void serviceRequest() //定义服务应答功能 { net_input = new
DataInputStream(clientInput); net_output = System.out; String user = read_net_input();
System.out.println(user+" connected!"); while(true) { String string;
if((string=read_net_input( ))==null) break; //如果客户机输入NULL,中断服务
write_net_output(user+":"+string); } System.out.println(user+" has
disconnected!"); } String read_net_input() { try {return net_input.readLine();}
catch(IOException e) {return null;} } void write_net_output(String string) {
net_output.println(string); net_output.flush(); } } 客户机程序源代码:
//client.java import java.io.*; import sun.net.*; class client extends NetworkClient //定义客户机类
{ DataInputStream net_input; PrintStream net_output; public static void main(String
args[])//获得服务器IP地址和客户机名 { if(args.length<2) { System.out.println( "To run,type: ");
System.out.println( "java client "); }
System.out.println( "Connecting..."); try {new client(args[0],args[1]);} catch
(Exception e) { System.out.println( "Unable to create NetworkClient."); return;
} } public client (String host,String username) throws IOException //与服务器链接功能
{ super(host,1111); if(serverIsOpen()) { System.out.println( "Connected to
server."); net_input = new DataInputStream(System.in); net_output = serverOutput;
net_output.println(username); chat(); } else System.out.println("Error:Could not
connect to server."); } void chat() //定义信息传递函数,当输入EXIT时,中断链接
{ String string; System.out.println( "Type EXIT to exit"); while(true) {
string=read_net_input(); if(string.equalsIgnoreCase("EXIT")) break;
write_net_output(string); } System.out.println("Disconnecting...");
close_server(); System.out.println("Done!"); } String read_net_input() { try
{return net_input.readLine();} catch(IOException e) {return null;} } void
write_net_output(String string) { net_output.println(string); net_output.flush(); } void
close_server() { try {closeServer();} catch(Exception e) {System.out.println("Unable
to close server.");} } }
----
|