wlh269 发表于 2013-1-15 03:00:48

Socket编程二

客户端读取本地目录的文件,传给服务端,服务端收到后将信息输出到控制台........
注意为什么客户端读取文件的时候要采取一定的编码方式....
服务端:
package com.wlh.socket;import java.io.DataInputStream;import java.io.IOException;import java.io.InputStream;import java.net.ServerSocket;import java.net.Socket;public class Server {/** * @param args */public static void main(String[] args) {Socket socket=null;InputStream is=null; DataInputStream dis=null;try {ServerSocket ss=new ServerSocket(8888); System.out.println("server started..."); socket = ss.accept();is = socket.getInputStream();   dis = new DataInputStream(is);String s;while((s=dis.readUTF())!=null){//System.out.println(s);    }} catch (IOException e) {e.printStackTrace();}finally{try {dis.close();is.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}

客户端:

package com.wlh.socket;import java.io.BufferedReader;import java.io.DataOutputStream;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.Socket;import java.net.UnknownHostException;public class Client {/** * @param args */public static void main(String[] args) {Socket socket=null; OutputStream os=null; DataOutputStream dos=null; BufferedReader br=null; String s;try { socket=new Socket("localhost",8888);os = socket.getOutputStream();dos = new DataOutputStream(os);//采用指点编码方式读取文件,不然会出现乱码   br = new BufferedReader(new InputStreamReader(new FileInputStream("D:\\logs\\server.xml"),"utf-8"));   while((s=br.readLine())!=null){   System.out.println(s);   dos.writeUTF(s);      }} catch (UnknownHostException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally{try {dos.close();br.close();os.close();} catch (IOException e) {e.printStackTrace();}}}}
页: [1]
查看完整版本: Socket编程二