TCP传输
Socket和ServerSocket,实现了两台机器间的套接字端点,绑定本机IP地址。建立客户端和服务端,客户端对应的对象是Socket,服务端对应的对象是ServerSocket。
//客户端部分
public class ClientA {
private String filePath ;
public String
getFilePath() {return filePath;}
public void setFilePath(String filePath ) { this. filePath = filePath;}
public String
getHost() {return host;}
public void setHost(String host ) { this. host = host;}
public int getPort() {return port; }
public void setPort(int port) {this.port = port ;}
private String host ;
private int port;
public static void main (String[] args) {
// TODO Auto-generated method stub
ClientA ca=new ClientA();
ca.setHost ("127.0.0.1") ;
ca.setPort (9527) ;
ca.setFilePath ("d:\\") ;
ca.upLoad ("N1.mp3") ;
}
//上传方法
private void upLoad(String fileName ) {
// TODO Auto-generated method stub
Socket
s =null;
try {
s =new Socket(host ,port );
File
fi =new File(filePath +fileName );
System .out.println( "文件大小:" +fi .length ());
FileInputStream
fis =new FileInputStream(new File(filePath+fileName)) ;
OutputStream
os =s .getOutputStream ();
int len;
byte[] buff =new byte[ 1024];
while((len =fis .read (buff)) >0 ){os.write( buff, 0, len);}
s .shutdownOutput ();
//获取服务器发来的消息。三次握手规则
InputStream
ip =s .getInputStream ();
byte[] buffser =new byte[ 1024];
System .out.println( new String(buffser,0,ip.read( buffser)));
//关闭资源
fis .close ();
os .close ();
ip .close ();
s .close ();
} catch (Exception e ) {
// TODO: handle exception
e .printStackTrace ();
}
}
}
//服务端部分,用了服务端继承Thread的办法
public class ServerA extends Thread {
public static void main (String[] args) {
// TODO Auto-generated method stub
ServerA
sa =new ServerA();
sa .start ();
}
@Override
public void run(){
try {
ServerSocket ss=new ServerSocket (9527) ;
Socket
s =ss .accept ();
//养成良好习惯,获取对方 ip并记录下来
String
ip =s .getInetAddress (). getHostAddress();
System .out.println( ip+ ">>>conected");
File
file =new File(ip +".mp3" );
//将客户端上传的资料写到存储区
FileOutputStream
fis =new FileOutputStream(new File("d:\\"+ file));
InputStream
ips =s .getInputStream ();
int len;
byte[] buff =new byte[ 1024];
while((len =ips .read (buff)) !=-1 )
fis .write (buff,0,len) ;
//通知客户端,上传成功
OutputStream
ops =s .getOutputStream ();
ops .write ("成功上传". getBytes());
//养成随手关闭资源的习惯
ops .close ();
fis .close ();
ips .close ();
s .close ();
} catch (Exception e ) {
// TODO: handle exception
e .printStackTrace ();
}
}
}
黑马程序员——网络编程之CTP传输,布布扣,bubuko.com