socket上傳下載
問題1 你好像沒有說清楚,不好作答。
問題2 可以在客戶端使用前做一個注冊,由伺服器產生一個身份識別碼,此後在客戶端每次連接伺服器時驗證這個注冊碼。數據一般來說都是要加密的,尤其是伺服器和客戶端之間的指令信息,如果明文傳送會很不安全。
問題3 在C/S架構里,一般都是客戶端主動去連接伺服器。即使是伺服器要向客戶端發送指令,也是在客戶端來連接時判斷是否有對應此客戶端的指令要下發。具體實現可以在服務端使用一個socket進行listen,當有客戶端來連接時啟動線程進行具體業務處理;而客戶端則定時向伺服器進行一次握手通訊,在握手的同時向伺服器詢問是否有可能存在的指令,如果有便進行指令下發;由於伺服器一直在listen,所以客戶端有要上傳的指令可以隨時連接並上傳。
問題4 這個可以在問題2里的注冊碼里包含,比如可更新的文件有3個,指定客戶端只能更新第一和第三個文件,你可以在注冊碼里一個特定欄位寫入"101",此後在客戶端連接伺服器時便可以知道自己能更新哪幾個文件了。
a.大型系統中的伺服器當然需要同時具備網路通信和資料庫訪問的功能。
因為要藉助資料庫來管理紛繁復雜的各種數據比如用戶信息、文件信息、軟體版本等,而沒有Socket網路通信就算不上是伺服器了。如果設計合理的話對速度是沒有影響的,這就需要你在架構和資料庫查詢方面下功夫做一些優化。
b.socket只是網路編程的一種技術,並不是架構,對應你客戶端使用C#的話,伺服器底層可用C++實現,架構方面可以研究一下完成埠。
❷ 要通過(socket)來傳輸文件這是什麼意思
SOCKET用於在兩個基於TCP/IP協議的應用程序之間相互通信。中文有的稱為套接字,你可以理解為一個插座和插頭,兩者匹配才能進行數據通信。 SOCKET最早出現在UNIX系統中,是UNIX系統主要的信息傳遞方式。在WINDOWS系統中,SOCKET稱為WINSOCK。
SOCKET有兩個基本概念:客戶方和服務方。當兩個應用之間需要採用SOCKET通信時,首先需要在兩個應用之間(可能位於同一台機器,也可能位於不同的機器)建立SOCKET連接,發起呼叫連接請求的一方為客戶方,接受呼叫連接請求的一方成為服務方。客戶方和服務方是相對的,同一個應用可以是客戶方,也可以是服務方。
在客戶方呼叫連接請求之前,它必須知道服務方在哪裡。所以需要知道服務方所在機器的IP地址或機器名稱,如果客戶方和服務方事前有一個約定就好了,這個約定就是PORT(埠號)。也就是說,客戶方可以通過服務方所在機器的IP地址或機器名稱和埠號唯一的確定方式來呼叫服務方。在客戶方呼叫之前,服務方必須處於偵聽狀態,偵聽是否有客戶要求建立連接。一旦接到連接請求,服務方可以根據情況建立或拒絕連接。連接方式有兩種,同步方式(Blocking)和(noBlocking).
客戶方發送的消息可以是文本,也可以是二進制信息流。當客戶方的消息到達服務方埠時,會自動觸發一個事件(event),服務方只要接管該事件,就可以接受來自客戶方的消息了。
❸ 怎樣用socket實現點對點的文件傳輸
在兩台計算機傳輸文件之前,必需得先有一台計算機建立套接字連接並綁定一個固定得埠,並在這個埠偵聽另外一台計算機的連接請求。
socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
socket.Blocking = true ;
IPEndPoint computernode1 = new IPEndPoint(serverIpadress, 8080);
socket.Bind(computernode1);
socket.Listen(-1);
當有其他的計算機發出連接請求的時候,被請求的計算機將對每一個連接請求分配一個線程,用於處理文件傳輸和其他服務。
while ( true )
{
clientsock = socket.Accept();
if ( clientsock.Connected )
{
Thread tc = new Thread(new ThreadStart(listenclient));
tc.Start();
}
}
下面的代碼展示了listenclient方法是如何處理另外一台計算機發送過來的請求。首先並對發送過來的請求字元串作出判斷,看看是何種請求,然後決定相應的處理方法。
void listenclient()
{
Socket sock = clientsock ;
try
{
while ( sock != null )
{
byte[] recs = new byte[32767];
int rcount = sock.Receive(recs,recs.Length,0) ;
string message = System.Text.Encoding.ASCII.GetString(recs) ;
//對message作出處理,解析處請求字元和參數存儲在cmdList 中
execmd=cmdList[0];
sender = null ;
sender = new Byte[32767];
string parm1 = "";
//目錄列舉
if ( execmd == "LISTING" )
{
ListFiles(message);
continue ;
}
//文件傳輸
if ( execmd == "GETOK" )
{
cmd = "BEGINSEND " + filepath + " " + filesize ;
sender = new Byte[1024];
sender = Encoding.ASCII.GetBytes(cmd);
sock.Send(sender, sender.Length , 0 );
//轉到文件下載處理
DownloadingFile(sock);
continue ;
}
}
}
catch(Exception Se)
{
string s = Se.Message;
Console.WriteLine(s);
}
}
至此,基本的工作已經完成了,下面我們看看如何處理文件傳輸的。
while(rdby < total && nfs.CanWrite)
{
//從要傳輸的文件讀取指定長度的數據
len =fin.Read(buffed,0,buffed.Length) ;
//將讀取的數據發送到對應的計算機
nfs.Write(buffed, 0,len);
//增加已經發送的長度
rdby=rdby+len ;
}
從上面的代碼可以看出是完成文件轉換成FileStream 流,然後通過NetworkStream綁定對應的套節子,最後調用他的write方法發送到對應的計算機。
我們再看看接受端是如何接受傳輸過來的流,並且轉換成文件的:
NetworkStream nfs = new NetworkStream(sock) ;
try
{
//一直循環直到指定的文件長度
while(rby < size)
{
byte[] buffer = new byte[1024] ;
//讀取發送過來的文件流
int i = nfs.Read(buffer,0,buffer.Length) ;
fout.Write(buffer,0,(int)i) ;
rby=rby+i ;
}
fout.Close() ;
從上面可以看出接受與發送恰好是互為相反的過程,非常簡單。
至此,單方向的文件傳輸就完成了,只需要在每個對等的節點上同時實現上面的發送和接受的處理代碼就可以做到互相傳輸文件了。
❹ socket
首先你得了解一些網路協議,比如TCP/IP和UDP協議,還有要知道計算機都有埠,而網路程序中套接字(Socket)用於將應用程序和埠連接起來。Socket是一個假想的連接裝置,就像插插頭的設備「插座」。
一般Socket用於網路的通訊,比如你要寫一個聊天室的程序,那發送和接受信息就需要用到Socket了。
❺ 關於用java的SOCKET傳輸文件
點對點傳輸文件
/*
import java.io.*;
import java.net.*;
import java.util.*;
*/
private HttpURLConnection connection;//存儲連接
private int downsize = -1;//下載文件大小,初始值為-1
private int downed = 0;//文加已下載大小,初始值為0
private RandomAccessFile savefile;//記錄下載信息存儲文件
private URL fileurl;//記錄要下載文件的地址
private DataInputStream fileStream;//記錄下載的數據流
try{
/*開始創建下載的存儲文件,並初始化值*/
File tempfileobject = new File("h:\\webwork-2.1.7.zip");
if(!tempfileobject.exists()){
/*文件不存在則建立*/
tempfileobject.createNewFile();
}
savefile = new RandomAccessFile(tempfileobject,"rw");
/*建立連接*/
fileurl = new URL("https://webwork.dev.java.net/files/documents/693/9723/webwork-2.1.7.zip");
connection = (HttpURLConnection)fileurl.openConnection();
connection.setRequestProperty("Range","byte="+this.downed+"-");
this.downsize = connection.getContentLength();
//System.out.println(connection.getContentLength());
new Thread(this).start();
}
catch(Exception e){
System.out.println(e.toString());
System.out.println("構建器錯誤");
System.exit(0);
}
public void run(){
/*開始下載文件,以下測試非斷點續傳,下載的文件存在問題*/
try{
System.out.println("begin!");
Date begintime = new Date();
begintime.setTime(new Date().getTime());
byte[] filebyte;
int onecelen;
//System.out.println(this.connection.getInputStream().getClass().getName());
this.fileStream = new DataInputStream(
new BufferedInputStream(
this.connection.getInputStream()));
System.out.println("size = " + this.downsize);
while(this.downsize != this.downed){
if(this.downsize - this.downed > 262144){//設置為最大256KB的緩存
filebyte = new byte[262144];
onecelen = 262144;
}
else{
filebyte = new byte[this.downsize - this.downed];
onecelen = this.downsize - this.downed;
}
onecelen = this.fileStream.read(filebyte,0,onecelen);
this.savefile.write(filebyte,0,onecelen);
this.downed += onecelen;
System.out.println(this.downed);
}
this.savefile.close();
System.out.println("end!");
System.out.println(begintime.getTime());
System.out.println(new Date().getTime());
System.out.println(begintime.getTime() - new Date().getTime());
}
catch(Exception e){
System.out.println(e.toString());
System.out.println("run()方法有問題!");
}
}
/***
//FileClient.java
import java.io.*;
import java.net.*;
public class FileClient {
public static void main(String[] args) throws Exception {
//使用本地文件系統接受網路數據並存為新文件
File file = new File("d:\\fmd.doc");
file.createNewFile();
RandomAccessFile raf = new RandomAccessFile(file, "rw");
// 通過Socket連接文件伺服器
Socket server = new Socket(InetAddress.getLocalHost(), 3318);
//創建網路接受流接受伺服器文件數據
InputStream netIn = server.getInputStream();
InputStream in = new DataInputStream(new BufferedInputStream(netIn));
//創建緩沖區緩沖網路數據
byte[] buf = new byte[2048];
int num = in.read(buf);
while (num != (-1)) {//是否讀完所有數據
raf.write(buf, 0, num);//將數據寫往文件
raf.skipBytes(num);//順序寫文件位元組
num = in.read(buf);//繼續從網路中讀取文件
}
in.close();
raf.close();
}
}
//FileServer.java
import java.io.*;
import java.util.*;
import java.net.*;
public class FileServer {
public static void main(String[] args) throws Exception {
//創建文件流用來讀取文件中的數據
File file = new File("d:\\系統特點.doc");
FileInputStream fos = new FileInputStream(file);
//創建網路伺服器接受客戶請求
ServerSocket ss = new ServerSocket(8801);
Socket client = ss.accept();
//創建網路輸出流並提供數據包裝器
OutputStream netOut = client.getOutputStream();
OutputStream doc = new DataOutputStream(
new BufferedOutputStream(netOut));
//創建文件讀取緩沖區
byte[] buf = new byte[2048];
int num = fos.read(buf);
while (num != (-1)) {//是否讀完文件
doc.write(buf, 0, num);//把文件數據寫出網路緩沖區
doc.flush();//刷新緩沖區把數據寫往客戶端
num = fos.read(buf);//繼續從文件中讀取數據
}
fos.close();
doc.close();
}
}
*/
❻ C# Winform 多線程 SOCKET 文件上傳,下載
這可是很麻煩的,自己到網上找吧
❼ c# c/s結構Socket上傳文件的代碼
發送端(client)
private void button2_Click(object sender, EventArgs e)
{
this.button2.Enabled = false;
Thread TempThread = new Thread(new ThreadStart(this.StartSend));
TempThread.Start();
}private void StartSend()
{
//FileInfo EzoneFile = new FileInfo(this.textBox1.Text);string path = @"E:old F directoryTangWeikangge ew1.jpg";
FileInfo EzoneFile = new FileInfo(path);
FileStream EzoneStream = EzoneFile.OpenRead();
int PacketSize = 100000;
int PacketCount = (int)(EzoneStream.Length / ((long)PacketSize));
// this.textBox8.Text = PacketCount.ToString();
// this.progressBar1.Maximum = PacketCount;
int LastDataPacket = (int)(EzoneStream.Length - ((long)(PacketSize * PacketCount)));
// this.textBox9.Text = LastDataPacket.ToString();
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("163.180.117.229"), 7000);Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
client.Connect(ipep);
// TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(EzoneFile.Name));
// TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(PacketSize.ToString()));
// TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(PacketCount.ToString()));
// TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(LastDataPacket.ToString()));
byte[] data = new byte[PacketSize];
for(int i=0; i<PacketCount; i++)
{
EzoneStream.Read(data, 0, data.Length);TransferFiles.SendVarData(client, data);
// this.textBox10.Text = ((int)(i + 1)).ToString();
// this.progressBar1.PerformStep();
}if(LastDataPacket != 0)
{
data = new byte[LastDataPacket];EzoneStream.Read(data, 0, data.Length);
TransferFiles.SendVarData(client,data);
// this.progressBar1.Value = this.progressBar1.Maximum;
}
client.Close();EzoneStream.Close();
this.button2.Enabled = true;
}接收端(server)
private void button2_Click(object sender, EventArgs e)
{
//int i = 0;
//FileStream recfs = new FileStream("E:\kangge.jpg", FileMode.OpenOrCreate);
//Byte[] recbyte = new Byte[2000000];
//Socket hostsocket = receive.Accept();
//BinaryWriter newfilestr = new BinaryWriter(recfs);
//hostsocket.Receive(recbyte, recbyte.Length, SocketFlags.None);
//for (i = 0; i < recbyte.Length; i++)
//{
// newfilestr.Write(recbyte, i, 1);
//}
//recfs.Close();//hostsocket.Shutdown(SocketShutdown.Receive);
//hostsocket.Close();this.button2.Enabled = false;
Thread TempThread = new Thread(new ThreadStart(this.StartReceive));
TempThread.Start();
}
private void StartReceive()
{
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("163.180.117.229"), 7000);Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
server.Bind(ipep);
server.Listen(10);
Socket client = server.Accept();
// IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;
// string SendFileName = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client));
// string BagSize = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client));
// int bagCount = int.Parse(System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client)));
// string bagLast = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client));
int file_name = 1;string fileaddr = "E:\old F directory\TangWei\Copy of kangge\" + file_name.ToString() + ".jpg";
FileStream MyFileStream = new FileStream(fileaddr, FileMode.Create, FileAccess.Write);// int SendedCount = 0;
while(true)
{
byte[] data = TransferFiles.ReceiveVarData(client);
if(data.Length == 0)
{
break;
}
else
{
// SendedCount++;
MyFileStream.Write(data, 0, data.Length);
}
}MyFileStream.Close();
client.Close();
this.button2.Enabled = true;
}公共類。 TransferFiles
class TransferFiles
{public TransferFiles()
{}
public static int SendVarData(Socket s, byte[] data) // return integer indicate how many data sent.
{
int total = 0;
int size = data.Length;
int dataleft = size;
int sent;
byte[] datasize = new byte[4];
datasize = BitConverter.GetBytes(size);
sent = s.Send(datasize);//send the size of data array.while (total < size)
{
sent = s.Send(data, total, dataleft, SocketFlags.None);
total += sent;
dataleft -= sent;
}return total;
}public static byte[] ReceiveVarData(Socket s) // return array that store the received data.
{
int total = 0;
int recv;
byte[] datasize = new byte[4];
recv = s.Receive(datasize, 0, 4, SocketFlags.None);//receive the size of data array for initialize a array.
int size = BitConverter.ToInt32(datasize, 0);
int dataleft = size;
byte[] data = new byte[size];while (total < size)
{
recv = s.Receive(data, total, dataleft, SocketFlags.None);
if (recv == 0)
{
data = null;
break;
}
total += recv;
dataleft -= recv;
}return data;
}
}
❽ java使用socket文件上傳
for(int size=0;size!=-1;size=fis.read(buf)){
output.write(buf,0,size);
output.flush();
}
for(int size=0;size!=-1;size=fis.read(buf))
在buf中讀取位元組;當buf沒有內容了,返回的-1;在這個之前,一直在循環;
output.write(buf,0,size);
output.flush();
把buf中道0開始到size個位元組的內容寫入輸出流緩沖中
並用 flush()確認發送到輸出流中了;
我的意見是output.write(buf,0,size);
改為output.write(buf);
你接受數據部分代碼怎麼寫的,是不是size等於一個大於1024的整數了而出錯
❾ Socket網路通信怎麼往伺服器上傳數據
//上傳文件
Socket socket = new Socket("192.168.0.240", 7878);
OutputStream outputStream = socket.getOutputStream();
String head = "Content-Length=" + audioFile.length()
+ ";filename=" + audioFile.getName()
+ ";sourceid=\r\n";
outputStream.write(head.getBytes());
PushbackInputStream inStream = new PushbackInputStream(
socket.getInputStream());
String response = StreaTool.readLine(inStream);
String[] items = response.split(";");
String position = items[1]
.substring(items[1].indexOf("=") + 1);
RandomAccessFile fileOutStream = new RandomAccessFile(
audioFile, "r");
fileOutStream.seek(Integer.valueOf(position));
byte[] buffer = new byte[1024];
int len = -1;
while ((len = fileOutStream.read(buffer)) != -1)
{
outputStream.write(buffer, 0, len);
}
fileOutStream.close();
outputStream.close();
socket.close();
audioFile.delete();
} catch (UnknownHostException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
❿ 利用java socket實現文件傳輸
1.伺服器端
package sterning;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerTest {
int port = 8821;
void start() {
Socket s = null;
try {
ServerSocket ss = new ServerSocket(port);
while (true) {
// 選擇進行傳輸的文件
String filePath = "D:\\lib.rar";
File fi = new File(filePath);
System.out.println("文件長度:" + (int) fi.length());
// public Socket accept() throws
// IOException偵聽並接受到此套接字的連接。此方法在進行連接之前一直阻塞。
s = ss.accept();
System.out.println("建立socket鏈接");
DataInputStream dis = new DataInputStream(new BufferedInputStream(s.getInputStream()));
dis.readByte();
DataInputStream fis = new DataInputStream(new BufferedInputStream(new FileInputStream(filePath)));
DataOutputStream ps = new DataOutputStream(s.getOutputStream());
//將文件名及長度傳給客戶端。這里要真正適用所有平台,例如中文名的處理,還需要加工,具體可以參見Think In Java 4th里有現成的代碼。
ps.writeUTF(fi.getName());
ps.flush();
ps.writeLong((long) fi.length());
ps.flush();
int bufferSize = 8192;
byte[] buf = new byte[bufferSize];
while (true) {
int read = 0;
if (fis != null) {
read = fis.read(buf);
}
if (read == -1) {
break;
}
ps.write(buf, 0, read);
}
ps.flush();
// 注意關閉socket鏈接哦,不然客戶端會等待server的數據過來,
// 直到socket超時,導致數據不完整。
fis.close();
s.close();
System.out.println("文件傳輸完成");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String arg[]) {
new ServerTest().start();
}
}
2.socket的Util輔助類
package sterning;
import java.net.*;
import java.io.*;
public class ClientSocket {
private String ip;
private int port;
private Socket socket = null;
DataOutputStream out = null;
DataInputStream getMessageStream = null;
public ClientSocket(String ip, int port) {
this.ip = ip;
this.port = port;
}
/** *//**
* 創建socket連接
*
* @throws Exception
* exception
*/
public void CreateConnection() throws Exception {
try {
socket = new Socket(ip, port);
} catch (Exception e) {
e.printStackTrace();
if (socket != null)
socket.close();
throw e;
} finally {
}
}
public void sendMessage(String sendMessage) throws Exception {
try {
out = new DataOutputStream(socket.getOutputStream());
if (sendMessage.equals("Windows")) {
out.writeByte(0x1);
out.flush();
return;
}
if (sendMessage.equals("Unix")) {
out.writeByte(0x2);
out.flush();
return;
}
if (sendMessage.equals("Linux")) {
out.writeByte(0x3);
out.flush();
} else {
out.writeUTF(sendMessage);
out.flush();
}
} catch (Exception e) {
e.printStackTrace();
if (out != null)
out.close();
throw e;
} finally {
}
}
public DataInputStream getMessageStream() throws Exception {
try {
getMessageStream = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
return getMessageStream;
} catch (Exception e) {
e.printStackTrace();
if (getMessageStream != null)
getMessageStream.close();
throw e;
} finally {
}
}
public void shutDownConnection() {
try {
if (out != null)
out.close();
if (getMessageStream != null)
getMessageStream.close();
if (socket != null)
socket.close();
} catch (Exception e) {
}
}
}
3.客戶端
package sterning;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
public class ClientTest {
private ClientSocket cs = null;
private String ip = "localhost";// 設置成伺服器IP
private int port = 8821;
private String sendMessage = "Windwos";
public ClientTest() {
try {
if (createConnection()) {
sendMessage();
getMessage();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
private boolean createConnection() {
cs = new ClientSocket(ip, port);
try {
cs.CreateConnection();
System.out.print("連接伺服器成功!" + "\n");
return true;
} catch (Exception e) {
System.out.print("連接伺服器失敗!" + "\n");
return false;
}
}
private void sendMessage() {
if (cs == null)
return;
try {
cs.sendMessage(sendMessage);
} catch (Exception e) {
System.out.print("發送消息失敗!" + "\n");
}
}
private void getMessage() {
if (cs == null)
return;
DataInputStream inputStream = null;
try {
inputStream = cs.getMessageStream();
} catch (Exception e) {
System.out.print("接收消息緩存錯誤\n");
return;
}
try {
//本地保存路徑,文件名會自動從伺服器端繼承而來。
String savePath = "E:\\";
int bufferSize = 8192;
byte[] buf = new byte[bufferSize];
int passedlen = 0;
long len=0;
savePath += inputStream.readUTF();
DataOutputStream fileOut = new DataOutputStream(new BufferedOutputStream(new BufferedOutputStream(new FileOutputStream(savePath))));
len = inputStream.readLong();
System.out.println("文件的長度為:" + len + "\n");
System.out.println("開始接收文件!" + "\n");
while (true) {
int read = 0;
if (inputStream != null) {
read = inputStream.read(buf);
}
passedlen += read;
if (read == -1) {
break;
}
//下面進度條本為圖形界面的prograssBar做的,這里如果是打文件,可能會重復列印出一些相同的百分比
System.out.println("文件接收了" + (passedlen * 100/ len) + "%\n");
fileOut.write(buf, 0, read);
}
System.out.println("接收完成,文件存為" + savePath + "\n");
fileOut.close();
} catch (Exception e) {
System.out.println("接收消息錯誤" + "\n");
return;
}
}
public static void main(String arg[]) {
new ClientTest();
}
}