⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 multithreadedremotefileclient.java

📁 java socket基础编程实例
💻 JAVA
字号:
   /*
	* Name of the Application     : MultithreadedRemoteFileClient.java
	* Development Environment     : Eclipse3.0M8
	* @Version 1.0
	* Describtion 
	* 
	*	1)The client requests Remote file from MultithreadedRemoteFileServer  
	*
	*
	* Creation / Modification History
	*	wsl	19:20 06/29/2004	Creation       
	*
	* Copyright ® 2004 www.cnlab.net
	* All right reserved. 
	*/
package net.cnlab.wsl.testsocket.multithread;

import java.io.*;
import java.net.*;

public class MultithreadedRemoteFileClient {
	
	protected String hostIp;
	protected int hostPort;
	
	protected BufferedReader socketReader;
	protected PrintWriter socketWriter;
	
	public MultithreadedRemoteFileClient(String aHostIp, int aHostPort) {
		hostIp = aHostIp;
		hostPort = aHostPort;
	}
	
	public static void main(String[] args) {
		MultithreadedRemoteFileClient remoteFileClient = new MultithreadedRemoteFileClient("127.0.0.1", 3001);
		remoteFileClient.setUpConnection();
		String fileContents = remoteFileClient.getFile("C:\\RemoteFile.txt");
		remoteFileClient.tearDownConnection();
		System.out.println(fileContents);
	}
	
	public void setUpConnection() {
		try {
			Socket client = new Socket(hostIp, hostPort);
			socketReader = new BufferedReader(new InputStreamReader(client.getInputStream()));
			socketWriter = new PrintWriter(client.getOutputStream());
			} catch (UnknownHostException e) {
				System.out.println("Error setting up socket connection: unknown host at " + hostIp + ":" + hostPort);
			} catch (IOException e) {
				System.out.println("Error setting up socket connection: " + e);
			}
	}
	
	public String getFile(String fileNameToGet) {
		StringBuffer fileLines = new StringBuffer();
		try {
			socketWriter.println(fileNameToGet);
			socketWriter.flush();
			String line = null;
			while ((line = socketReader.readLine()) != null)
				fileLines.append(line + "\n");
		} catch (IOException e) {
			System.out.println("Error reading from file: " + fileNameToGet);
		}
		return fileLines.toString();
	}
	
	public void tearDownConnection() {
		try {
			socketWriter.close();
			socketReader.close();
		} catch (IOException e) {
				System.out.println("Error tearing down socket connection: " + e);
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -