Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import java.net.InetAddress;
Import Java.net.ServerSocket;
Import Java.net.Socket;
Import java.net.UnknownHostException;
Import Org.junit.Test;
/*
* The client sends text to the server, and the server turns the text into uppercase and returns it to the client
*/
public class TCPExer2 {
/*
* Client
*/
@Test
public void Client () {
Socket socket = NULL;
OutputStream OS = null;
InputStream is = null;
try {
Socket = new Socket (Inetaddress.getbyname ("127.0.0.1"), 9999);
OS = Socket.getoutputstream ();
Os.write ("Abcdefght". GetBytes ());
Socket.shutdownoutput ();
is = Socket.getinputstream ();
Byte[] B = new byte[1024];
int Len;
while (len = Is.read (b))! =-1) {
String str = new string (B,0,len);
System.out.println ("I am the client, received the return data from the server:" + str);
}
} catch (Unknownhostexception e) {
E.printstacktrace ();
} catch (IOException e) {
E.printstacktrace ();
} finally {
if (is = null) {
try {
Is.close ();
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
if (OS! = null) {
try {
Os.close ();
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
if (socket! = NULL) {
try {
Socket.close ();
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}
}
/*
* Service Side
*/
@Test
public void server () {
ServerSocket SS = null;
Socket s = null;
InputStream is = null;
OutputStream OS = null;
try {
SS = new ServerSocket (9999);
s = ss.accept ();
is = S.getinputstream ();
Byte[] B = new byte[1024];
int Len;
String str = NULL;
while (len = Is.read (b))! =-1) {
str = new String (B,0,len);
System.out.println ("I am the server, receiving information from the client:" + str);
str = Str.touppercase ();
}
S.shutdowninput ();
OS = S.getoutputstream ();
Os.write (Str.getbytes ());
} catch (IOException e) {
E.printstacktrace ();
} finally {
if (OS! = null) {
try {
Os.close ();
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
if (is = null) {
try {
Is.close ();
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
if (s! = null) {
try {
S.close ();
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
if (ss! = null) {
try {
Ss.close ();
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}
}
}
TCP Exercise 2: The client sends text to the server, and the server turns the text into uppercase and then back to the client