Author: gnuhpc
Source: http://www.cnblogs.com/gnuhpc/
Client:
Import java.net. Socket;
Import java.net. inetaddress;
Import java.net. unknownhostexception;
Import java. Io. outputstream;
Import java. Io. bufferedreader;
Import java. Io. inputstream;
Import java. Io. inputstreamreader;
Import java. Io. printwriter;
Import java. Io. ioexception;
Public class tcpclient {
Public static void main (string [] ARGs) throws ioexception {
Try {
Byte A [] = {127,0, 0, 1 };
Inetaddress address = inetaddress. getbyaddress ();
Socket socket = new socket (address, 9876 );
Outputstream OS = socket. getoutputstream ();
Printwriter out = new printwriter (OS, true );
Inputstream is = socket. getinputstream ();
Inputstreamreader ISR = new inputstreamreader (is );
Bufferedreader in = new bufferedreader (ISR );
String line;
Line = "A line sent by the client ";
Out. println (line );
Line = in. Readline ();
System. Out. println ("client got:" + line );
Out. Close ();
In. Close ();
Socket. Close ();
} Catch (unknownhostexception e ){
System. Out. println (E );
} Catch (ioexception e ){
System. Out. println (E );
}
}
}
Server:
Import java.net. serversocket;
Import java.net. Socket;
Import java. Io. bufferedreader;
Import java. Io. inputstream;
Import java. Io. inputstreamreader;
Import java. Io. ioexception;
Import java. Io. outputstream;
Import java. Io. printwriter;
Public class tcpserver {
Public static void main (string [] ARGs ){
Try {
Serversocket = new serversocket (9876 );
Socket socket =Serversocket. Accept ();
/* Same as client */
Inputstream is = socket. getinputstream ();
Inputstreamreader ISR = new inputstreamreader (is );
Bufferedreader in = new bufferedreader (ISR );
Outputstream OS = socket. getoutputstream ();
Printwriter out = new printwriter (OS, true );
String line;
While (line = in. Readline ())! = NULL ){
System. Out. println ("server got:" + line );
Line = "A line sent by the server ";
Out. println (line );
}
Out. Close ();
In. Close ();
Socket. Close ();
Serversocket. Close ();
} Catch (ioexception e ){
System. Out. println (E );
System. Exit (1 );
}
}
}
Author: gnuhpc
Source: http://www.cnblogs.com/gnuhpc/