您的位置:首页 > 理论基础 > 计算机网络

网络编程TCP(六)

2015-08-16 21:10 627 查看

从客户端发送文件到服务器,服务器保存文件到本地。并返回“保存成功”给客户端。并关闭相应连接。

package com;

import java.io.File;
import java.io.FileInputStream;
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 org.junit.Test;

//从客户端发送文件到服务器,服务器保存文件到本地。并返回“保存成功”给客户端。并关闭相应连接
public class TestTcp3 {
@Test
public void client(){
Socket socket=null;
OutputStream os=null;
FileInputStream fis=null;
InputStream is=null;
try {
//1创建socket对象
socket=new Socket(InetAddress.getByName("127.0.0.1"),8989);
//2获取本地图片
os=socket.getOutputStream();
fis=new FileInputStream(new File("ip标示.png"));
byte[]b=new byte[1024];
int len;
while((len=fis.read(b))!=-1){
os.write(b,0,len);
}
//5显示告诉服务端。我发送完了。
socket.shutdownOutput();

//3接受服务端信息
is=socket.getInputStream();
byte[] b1=new byte[1024];
int len1;
while((len1=is.read(b1))!=-1){
String str=new String(b1,0,len1);
System.out.println(str);
}

} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
//4关闭
if(is!=null){
try {
is.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(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();
}
}
}
}
@Test
public void server(){
ServerSocket server=null;
Socket socket=null;
InputStream is=null;
FileOutputStream fos=null;
OutputStream os=null;
try {
//定义端口号供客户端进行通讯
server=new ServerSocket(8989);
//调用accept方法获取一个socket对象
socket=server.accept();
//将从客户端发送的数据信息保存到本地
is=socket.getInputStream();
fos=new FileOutputStream(new File("2.png"));
byte[] b=new byte[1024];
int len;
while((len=is.read(b))!=-1){
fos.write(b,0,len);
}
//回馈客户端
os=socket.getOutputStream();
os.write("nifasongdetupianwojieshoudaole!".getBytes());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
//关闭
if(os!=null){
try {
os.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(is!=null){
try {
is.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(server!=null){
try {
server.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}






tcp到此结束!!!!!!。之后就是udp通讯协议。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: