我写一个传送和接收文件的程序,想点对点的不用另外加服务器,所以就直接把客户端和服务器端写在同一个程序中,但是有个问题,就是服务器端在执行.accept();这个方法的时候,会一直阻塞,直到有收到客户端请求为止(一旦阻塞就无法去执行发送文件那个进程),
所以我想必须把他们放到单独的线程中,但是服务器这个线程怎么写啊!..........困惑中
------解决方案--------------------
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());
}
}catch(Exception e){System.out.println( "接收出错! ");}
finally
{
clears();
}
}
void clears()
{
try
{
dout.close();
din.close();
mySock.close();
}catch(Exception e){System.out.println( "关闭出错 ");}
}
}