posts - 241,  comments - 116,  trackbacks - 0
/*
TCP通讯

[示例]:传送文本文件 (客户端)
*/

import java.net.*;
import java.io.*;
class Demo
{
  public static void main(String[] args) throws Exception
  {
    new FileClient();
  }
}

class FileClient  //客户端
{
  FileClient() throws Exception
  {
    s.op("客户端启动....");
    client();
  }
 
  public void client()throws Exception
  {
    Socket sock = new Socket("192.168.1.3",10006);//指定服务器地址和接收端口
    
    //将c盘一个文本文件发送到服务器端
    BufferedReader bufr = new BufferedReader(new FileReader("c:\\abcd.java"));
    
    //定义socket输出流,将数据发给服务端
    //BufferedWriter bufwOut=new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
    //我们不用它了,用PrintWriter更方便,因为println方法自动换行和刷新缓冲区9
    PrintWriter priOut= new PrintWriter(sock.getOutputStream(),true);//将数据发送到socket输出流
    
    String fileLine = null;
    while(true)
    {
      fileLine = bufr.readLine(); //读文本文件
      if(fileLine!=null)
      {
        priOut.println(fileLine); //将一行文本写入socket输出流      
      }
      else
      {
        break;
      }    
    }
    //文件传送完后,告诉服务端,"我发完了",也就是加一个结束标记
    //priOut.println("*#over886*#");  这种方式不好,服务端怎么知道结束标记是什么,不方便
    
    sock.shutdownOutput(); //结束TCP套接字,之前写入的数据都将被发送,并且后跟TCP连接终止标记
    BufferedReader bufrIn=new BufferedReader(new InputStreamReader(sock.getInputStream()));    
    String inStr = bufrIn.readLine(); //服务端此时应该返回字符,比如"发送成功"
    s.op(inStr);   //显示服务器返回的字符信息 "上传成功."
    bufr.close();
    sock.close();
  }
}

class s  
{
  public static void op(Object obj) //打印
  {
    System.out.println(obj);
  }
}
/*
这里我们没有考虑客户端的文件名,和客户端判断是否有重名文件,我们指定了文件名和路径

[示例]:传送文本文件 (服务端)
*/
import java.net.*;
import java.io.*;
class Demo
{
  public static void main(String[] args) throws Exception
  {
    new FileServer();
  }
}

class FileServer  //服务端
{
  FileServer() throws Exception
  {
    s.op("服务端启动......");
    server();
  }

  public void server() throws Exception
  {
    ServerSocket serversock = new ServerSocket(10006);
    Socket sock = serversock.accept();
    
    String ip = sock.getInetAddress().getHostAddress();
    s.op("来自客户端IP "+ip+" 的文件");
    
    BufferedReader bufrIn = new BufferedReader(new InputStreamReader(sock.getInputStream()));
    PrintWriter priFileOut = new PrintWriter(new FileWriter("d:\\getFile.java"),true);
    String inStr = null;
    while(true)
    {
      inStr = bufrIn.readLine();
      if(inStr!=null)
      {
        s.op(inStr); //将客户端的文本数据打印到控制台看看,对于大文件,本行代码可注释掉
        priFileOut.println(inStr); //写到文件中          
      }
      else
      {
        break;
      }
    }  
    //文件保存完给客户端一个返回信息
    PrintWriter priOut = new PrintWriter(sock.getOutputStream(),true); //注意别丢了参数true
    priOut.println("上传成功.");//如果没有true参数,字符在缓冲区中不刷新的
    sock.close();
    priFileOut.close();
    serversock.close();
  }
}

class s
{
  public static void op(Object obj) //打印
  {
    System.out.println(obj);
  }
}
posted on 2012-02-01 10:25 墙头草 阅读(2092) 评论(2)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航:
 
人人游戏网 软件开发网 货运专家