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;
/*
* TCP Programming Example two:
* The client sends messages to the server, and the server prints the information to the console, sending the message "received" to the client.
*/
public class TestTCP2 {
/*
* Client
*/
@Test
public void Client () {
Socket socket = NULL;
OutputStream OS = null;
InputStream is = null;
try {
Socket = new Socket (Inetaddress.getbyname ("127.0.0.1"), 9898);
OS = Socket.getoutputstream ();
String str = "I am the client, please receive." ";
Os.write (Str.getbytes ());
Shutdownoutput (): Display tells the server side I've finished outputting
Socket.shutdownoutput ();
is = Socket.getinputstream ();
Byte[] B = new byte[100];
int Len;
while (len = Is.read (b))! =-1) {
str = new String (b, 0, Len);
System.out.println (str);
}
} catch (Unknownhostexception e) {
E.printstacktrace ();
} catch (IOException e) {
E.printstacktrace ();
} finally {
if (is = null) {
try {
Is.close ();
} catch (IOException e) {
E.printstacktrace ();
}
}
if (OS! = null) {
try {
Os.close ();
} catch (IOException e) {
E.printstacktrace ();
}
}
if (socket! = NULL) {
try {
Socket.close ();
} catch (IOException e) {
E.printstacktrace ();
}
}
}
}
/*
* Server-side
*/
@Test
public void server () {
ServerSocket SS = null;
Socket socket = NULL;
InputStream is = null;
OutputStream OS = null;
try {
SS = new ServerSocket (9898);
Socket = Ss.accept ();
is = Socket.getinputstream ();
Byte[] B = new byte[100];
int Len;
while (len = Is.read (b))! =-1) {
String str = new string (b, 0, Len);
System.out.println (str);
}
OS = Socket.getoutputstream ();
Os.write ("Message received. ". GetBytes ());
This side also shows the tell the client, I finished the output
Socket.shutdownoutput ();
} catch (IOException e) {
E.printstacktrace ();
} finally {
if (OS! = null) {
try {
Os.close ();
} catch (IOException e) {
E.printstacktrace ();
}
}
if (is = null) {
try {
Is.close ();
} catch (IOException e) {
E.printstacktrace ();
}
}
if (socket! = NULL) {
try {
Socket.close ();
} catch (IOException e) {
E.printstacktrace ();
}
}
if (ss! = null) {
try {
Ss.close ();
} catch (IOException e) {
E.printstacktrace ();
}
}
}
}
}
TCP Programming 2: The client sends messages to the server, the server prints the information to the console, and sends the "received message" to the client