/*
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
墻頭草 閱讀(2099)
評論(2) 編輯 收藏