日期:2014-05-20  浏览次数:20705 次

socket的面试题求解
使用socket,实现从客户端传一文件到服务器端,并在服务器端控制台打印出来,文件为:D:/data.txt   内容为:hello!
服务器和客户端都在本地
——————————————
程序怎么写   请指导下?

------解决方案--------------------
import java.net.*;
import java.io.*;
public class Server
{
private ServerSocket server;
private Socket you;
private receive rec;
public Server()
{
try
{
server = new ServerSocket(2007);
System.out.println( "服务器运行中,监听端口:2007...... ");
while(true)
{
you = server.accept();
if(you != null)
{
System.out.println( "有客户连接启动接收线程... ");
new Thread(new receive(you)).start();
System.out.println( "接收文件内容如下: ---> 服务器继续监听中... ");
}
}
}catch(Exception e){System.out.println( "服务端运行出错! ");}
}

public static void main(String args[])
{
new Server();
}
}

class receive implements Runnable
{
private File files;
private DataInputStream din = null;
private DataOutputStream dout = null;
private Socket mySock = null;
private int str = 1;
public receive(Socket you)
{
this.mySock = you;
//files = new File( "d:\\data.txt ");
}

public void run()
{
try
{
din = new DataInputStream(mySock.getInputStream());
dout = new DataOutputStream(mySock.getOutputStream());

while(true)
{
if((str=din.readInt()) == 0)
break;
System.out.println( " " + din.readUTF());
}
clears();
}catch(Exception e){System.out.println( "接收出错! ");}
finally
{
clears();
}

}

void clears()
{
try
{
dout.close();
din.close();
mySock.close();
}catch(Exception e){System.out.println( "关闭出错 ");}
}

}
------解决方案--------------------
import java.net.*;
import java.io.*;
public class Client
{
private Socket you;
SendData sends;

public Client()
{
try
{
you = new Socket( "localhost ",2007);
System.out.println( "连接服务器监听端口:2007...... ");
if(you != null)
{
System.out.println( "连接成功,启动发送线程... ");
new Thread(new SendData(you)).start();
System.out.println( "发送完毕!关闭线程... ");
}
}catch(Exception e){System.out.println( "服务端运行出错! ");}
}

public static void main(String args[])
{
new Client();
}
}

class SendData implements Runnable
{
private File files;
private BufferedReader bin = null;
private DataInputStream din = null;
private DataOutputStream dout = null;
private Socket mySock = null;
private String data = " ";
public SendData(Socket you)
{
this.mySock = you;
files = new File( "d:\\data.txt ");
}

public void run()
{
try
{
bin = new BufferedReader(new InputStreamReader(new FileInputStream(files)));
din = new DataInputStream(mySock.getInputStream());
dout = new DataOutputStream(mySock.getOutputStream());
while((data = bin.readLine()) != null)
{
dout.writeInt(1);
dout.writeUTF(data);
}
dout.writeInt(0);
clears();
}catch(Exception e){}