场景:
使用tcp网络编程时,使用socket模拟,一个作为客户端,一个作为服务器接收端
原因:
必须先开启服务端,才可以开启客户端
就是先启动服务器端的@Test,然后再启动客户端的@Test
代码如下:
客户端:
package socket;
import java.io.ByteArrayInputStream;
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;
public class TCP2 {
@Test
public void client() {
FileInputStream fis =null;
InetAddress inet=null;
Socket socket = null;
OutputStream os =null;
//创建输入流:
try {
fis = new FileInputStream("src/bz2.jpg");
inet = InetAddress.getByName("127.0.0.1");
socket = new Socket(inet,9090);
//获取输出流
os = socket.getOutputStream();
//开始输出
byte[] cb=new byte[1024];
int len=0;
while((len=fis.read(cb))!=-1){
os.write(cb,0,len);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
//4.资源的关闭
if(os != null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(socket != null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fis!=null) {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
服务器端:先启动这个
package socket;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import org.junit.Test;
public class Tcp2Server {
@Test
public void server() {
ServerSocket serverSocket =null;
Socket socket = null;
InputStream is=null;
FileOutputStream fos=null;
try {
serverSocket = new ServerSocket(9090);
//表示接受
socket = serverSocket.accept();
//输入流
is = socket.getInputStream();
fos=new FileOutputStream("src/bz10.jpg");
byte[] buffer=new byte[1024];
int len=0;
while((len=is.read(buffer))!=-1) {
fos.write(buffer, 0, len);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
// ServerSocket serverSocket =null;
// Socket socket = null;
// InputStream is=null;
// FileOutputStream fos=null;
if(is!=null) {
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(fos!=null) {
try {
fos.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(serverSocket!=null) {
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}