socket编程

客户端:
package j2se;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class RemoteFileClient {

protected String ip;
protected int port;
protected BufferedReader socketReader;
protected PrintWriter socketWriter;

public RemoteFileClient(String ip,int port){
this.ip = ip;
this.port = port;
}

public void setUpConnection() throws UnknownHostException, IOException{
Socket socket = new Socket(ip,port);
socketReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
socketWriter = new PrintWriter(socket.getOutputStream());

}

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(Exception e){
e.printStackTrace();
}
return fileLines.toString();
}

public void tearDownConnection() throws IOException{
socketWriter.close();
socketReader.close();
}
/**
* @param args
* @throws IOException
* @throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException, IOException {
// TODO Auto-generated method stub
RemoteFileClient remoteFileClient = new RemoteFileClient("10.32.146.108",3002);
remoteFileClient.setUpConnection();
String strFile = remoteFileClient.getFile("c:\\a.txt");
remoteFileClient.tearDownConnection();

System.out.println(strFile);
}

}

服务器端:
package j2se;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class RemoteFileServer {

protected int listenPort = 3002;

public void acceptConnection() throws IOException{
ServerSocket server = new ServerSocket(listenPort);
Socket incomingConnection = null;
while(true){
incomingConnection = server.accept();
handleConnection(incomingConnection);
}
}

public void handleConnection(Socket incomingConnection) throws IOException{
BufferedReader streamReader = new BufferedReader(new InputStreamReader(incomingConnection.getInputStream()));

FileReader fileReader = new FileReader(new File(streamReader.readLine()));

BufferedReader bufferReader = new BufferedReader(fileReader);

PrintWriter streamWriter = new PrintWriter(incomingConnection.getOutputStream());
String line = null;
while((line = bufferReader.readLine()) != null){
streamWriter.write(line+"\n");
}

fileReader.close();
streamWriter.close();
streamReader.close();
}
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
RemoteFileServer server = new RemoteFileServer();
server.acceptConnection();

}

}

你可能感兴趣的:(java,编程,.net,socket,J2SE)