Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;
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;
/*
* Server-side read pictures and sent to the client, the client save the picture to the local
* Import a picture in the current project directory, named 1.jpg
*/
public class TCPExer1 {
/*
* Client
*/
@Test
public void Client () {
Socket socket = NULL;
FileOutputStream fos = null;
InputStream is = null;
try {
Socket = new Socket (Inetaddress.getbyname ("127.0.0.1"), 9090);
FOS = new FileOutputStream (New File ("e:\\3.jpg"));
is = Socket.getinputstream ();
Byte[] B = new byte[1024];
int Len;
while (len = Is.read (b))! =-1) {
Fos.write (b, 0, Len);
}
} catch (Unknownhostexception e) {
E.printstacktrace ();
} catch (FileNotFoundException e) {
E.printstacktrace ();
} catch (IOException e) {
E.printstacktrace ();
} finally {
if (fos! = null) {
try {
Fos.close ();
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
if (fos! = null) {
try {
Is.close ();
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
if (fos! = null) {
try {
Socket.close ();
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}
}
/*
* Server-side
*/
@Test
public void server () {
ServerSocket SS = null;
Socket socket = NULL;
FileInputStream FIS = null;
OutputStream OS = null;
try {
SS = new ServerSocket (9090);
Socket = Ss.accept ();
FIS = new FileInputStream (New File ("2.jpg"));
OS = Socket.getoutputstream ();
Byte[] B = new byte[1024];
int Len;
while (len = Fis.read (b))! =-1) {
Os.write (b, 0, Len);
}
Socket.shutdownoutput ();
} catch (FileNotFoundException e) {
E.printstacktrace ();
} catch (IOException e) {
E.printstacktrace ();
} finally {
if (OS! = null) {
try {
Os.close ();
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
if (FIS! = null) {
try {
Fis.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 ();
}
}
if (ss! = null) {
try {
Ss.close ();
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}
}
}
TCP Exercise 1: Server-side reads the picture and sends it to the client, the client saves the picture to the local