java 中的cs_Java在CS网络中的应用

try

{

listen_socket=newServerSocket(port);

}

catch(IOExceptione)fail(e,

"Exceptioncreatingserversocket");

System.out.println("Server:

listeningonport"+port);

This.start();

}

该线程一直循环执行,监听并接受客户机发出的连接请求。对每一个连接,均产生一个连接对象与之对应,通过Socket通道进行通信。

*/

publicvoidrun()

{

try

{

while(true)

{

Socketclient_socket=listen_socket.accept();

Connectionc=newConnection(client_socket);

}

}

catch(IOExceptione)fail

(e,"Exceptionwhilelisteningforconnections")

}

//启动服务器主程序

publicstaticvoidmain(Stringargs[])

{

intport=0;

if(args.length==1)

{

tryport=Integer.parseInt(args[0]);

catch(NumberFormatExceptione)port=0;

}

newServer(port);

}//Endofthemain

}//EndofServerclass

//以下定义了Connection类,

它是用来处理与客户机的所有通信的线程。

classConnectionextendsThread

{

protectedSocketclient;

protectedDataInputStreamin;

protectedPrintStreamout;

//初始化通信流并启动线程

publicConnection(Socketclient_socket)

{

client=client_socket;

try

{

in=newDataInputStream(client.getinputStream());

out=newPrintStream(client.getOutputStream());

}

catch(IOExceptione)

{

tryclient.close();

catch(IOExceptione2);

System.err.println

("Exceptionwhilegettingsocketstreram:"+e);

Return;

}

this.start;

}//EndofConnectionmethod

//服务例程:读出一行文本;

反转文本;返回文本。

publicvoidrun()

{

Stringline;

StringBufferrevline;

intlen;

try

{

for(;;)

{

//Readaline

line=in.readline();

if(line==null)break;

//Reversetheline

len=line.length();

revline=newStringBuffer(len);

for(inti=len-1;i>=0;i--)

revline.insert(len-1-I;line.charAt(i));

//Writeoutthereverseline

out.println(revline);

}

catch(IOExceptione);

finallytryclient.close();

catch(IOExceptione2);

}//Endofrunmethod

}//EndofConnectionclass

//Client.java

importjava.io.*;

importjava.net.*;

publicclassClientextends

{

publicstaticfinalintDefault_Port=6543;

//定义出错例程

publicstaticfinalvoidusage()

{

System.out.println("Usage:

JavaClient[]");

System.exit(0);

}

publicstaticvoidmain(Stringargs[])

{

intport=Default_Port;

Sockets=null;

//解析端口参数

if((args.length!=1)&&

(args.length!=2))usage();

if(args.length==1)

port=Default_Port;

else

{

tryport=Integer.parseInt(args[1]);

catch(NumberFormaatExceptione)usage();

}

try{

//产生一个Socket,通过指定的端口与主机通信。

s=newSocket(args[0],port);

//产生用于发出和接收的文本字符流

DataInputStreamsin=new

DataInputStream(s.getInputStream());

PrintStreamsout=new

DataInputStream(s.getInputStream());

//从控制台读入字符流

DataInputStreamin=new

你可能感兴趣的:(java,中的cs)