Socket client=server.accept()/逗返神/监听端口,一旦取得山亏连接则获得客户端的socket连接对象client
客户端: Socket s=new Socket(ip,port)//要连接的服务器的ip以及端口号
如果正常连接上之后,socket的对象可以获得InputStream和OutputStreame,然后就可以进行通信了
完成通信之后,执世陵行socket对象的close()方法关闭连接,完成一次完整的socket连接
//以前写的一个文件传扰困输的小程序,有客户端缓手念和服务器端两部分,服务器可//以一直运行,客户端传输完一个后退出,当然你也可以根据你的需要改。//服务器端可以支持多个客户端同时上传,用到了多线程
/薯或**
* 文件传输,客户端
* @aurth anyx
*/
//package per.anyx.ftp
import java.net.*
import java.io.*
public class FtpClient{
public static void main(String[] args){
if(args.length != 3){
System.out.println("Usage: FtpClient host_add host_port src_file")
System.exit(0)
}
File file = new File(args[2])
if(!file.exists() || !file.isFile()){
System.out.println("File \"" + args[2] + "\" does not exist or is not a normal file.")
System.exit(0)
}
Socket s = null
FileInputStream in = null
OutputStream out = null
try{
s = new Socket(args[0], Integer.parseInt(args[1]))
in = new FileInputStream(file)
out = s.getOutputStream()
byte[] buffer = new byte[1024*8]
int len = -1
System.out.println("File tansfer statr...")
while((len=in.read(buffer)) != -1){
out.write(buffer, 0, len)
}
System.out.println("File tansfer complete...")
}catch(Exception e){
System.out.println("Error: " + e.getMessage())
System.exit(1)
}finally{
try{
if(in != null) in.close()
if(out != null) out.close()
if(s != null) s.close()
}catch(Exception e){}
}
}
}
/**
* 文件传输,服务器端
* @aurth anyx
*/
//package per.anyx.ftp
import java.net.*
import java.io.*
public class FtpServer{
public static void main(String[] args){
if(args.length != 1){
System.out.println("Usage: FtpServer server_port")
System.exit(0)
}
ServerSocket ss = null
try{
ss = new ServerSocket(Integer.parseInt(args[0]))
System.out.println("FtpServer start on port ..." + args[0])
while(true){
Socket s = ss.accept()
new FtpThread(s).start()
System.out.println(s.getInetAddress().getHostAddress() + " connected.")
}
}catch(Exception e){
System.out.println("Error: " + e.getMessage())
}finally{
try{
if(ss != null) ss.close()
}catch(Exception e){}
}
}
}
class FtpThread extends Thread{
Socket s
long fileName = 0
public FtpThread(Socket s){
this.s = s
}
public void run(){
FileOutputStream out = null
InputStream in = null
File file = null
do{
file = new File("" + (fileName++))
}while(file.exists())
try{
out = new FileOutputStream(file)
in = s.getInputStream()
byte[] buffer = new byte[1024*8]
int len = -1
while((len=in.read(buffer)) != -1){
out.write(buffer, 0, len)
}
}catch(Exception e){
System.out.println("Error: " + e.getMessage())
}finally{
try{
if(in != null) in.close()
if(out != null) out.close()
if(s != null) s.close()
System.out.println(s.getInetAddress().getHostAddress() + " connect closed..")
}catch(Exception e){}
}
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)