1、官方 Socket 文件(Client 端用來與 Server 連線的 Socket)
2、官方 ServerSocket 文件(Server 端用來接受 Client 端連線的 Socket)
Client 端的語法:
InetAddress addressOfServer = InetAddress.getByName("127.0.0.1"); int portOfServer = 22; // File to be transmitted File file = new File("/home/user/test.img"); // Create buffer byte[] buffer = new byte[2048]; int bytesReaded; // Socket connection for connecting to the server Socket socketFromClient = null; // Output stream for transmitting file to the server DataOutputStream outputStream = null; // Input stream for reading local file FileInputStream fis = null; try { // Create socket socketFromClient = new Socket(addressOfServer, portOfServer); // Create output stream for transmitting file outputStream = new DataOutputStream(socketFromClient.getOutputStream()); // Create input Stream for reading file FileInputStream fis = new FileInputStream(file); // Start transmitting while( (bytesReaded = fis.read(buffer)) > -1 ) { outputStream.write(buffer, 0, bytesReaded); outputStream.flush(); } } finally { // Close the stream objects if(outputStream != null) outputStream.close(); if(fis != null) fis.close(); } // Close the connection of socket if(socketFromClient != null) socketFromClient.close();
Server 端語法:
int portOfServer = 22; // Start listening to port 22 ServerSocket serverSocket = new ServerSocket(serverPort); Socket clientSocket = serverSocket.accept(); // Reader for accepting the transmission from client BufferedInputStream bis = null; DataInputStream dis = null; // File writer for writing the file transmitted from the client File writtenFile = null; FileWriter fw = null; BufferedWriter bw = null; try { // Get the address of the connecting client String addressOfClient = clientSocket.getRemoteSocketAddress().toString(); // Get the stream which the client tranmits bis = new BufferedInputStream(clientSocket.getInputStream()); dis = new DataInputStream(bis); // Create file writer writtenFile = new File("transmittedFile"); fw = new FileWriter(writtenFile); bw = new BufferedWriter(fw); // Create buffer byte[] buffer = new byte[2048]; int bytesReaded; // Accept and write the file while( (bytesReaded = dis.read(buffer)) > -1) { bw.write(buffer, 0, bytesReaded); bw.flush(); } }finally { // Close the stream and writer objects if(bw != null) bw.close(); if(fw != null) fw.close(); if(dis != null) dis.close(); if(bis != null) bis.close(); }
如果只是要傳送字串資料,而不是傳送檔案的話,作法好像是一樣的,可以參考以下的連結。
參考資料:
3、簡單的Socket Client Server
沒有留言:
張貼留言