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

java中的客户服务器程序
我在Ubuntu系统下安装的eclipse环境,在上面用线程方式将客户端程序与服务器端程序写在一个程序中的,可是调不通,还请各位高手指点。我的程序:
package Server_ClientDemo1;
import java.io.*;
import java.net.*;
public class Server_ClientDemo1 {
  public static void main(String[] args){
Server ser=new Server();
Client clt=new Client();
Thread th1=new Thread(ser);
Thread th2=new Thread(clt);
th1.start();
th2.start();
  }
}
class Server implements Runnable{
int index=0;
int serverPort=100;
int clientPort=200;
int b_size=60;
byte[] buf=new byte[b_size];
public void run(){
try{
InetAddress iads=InetAddress.getByName("127.0.0.1");
DatagramSocket dSocket=new DatagramSocket(serverPort);
int c;
while((c=System.in.read())!='\n'){
switch(c){
case '\r':break;
default:buf[index]=(byte)c;
index++;
}
}
DatagramPacket dp=new DatagramPacket(buf,index,iads,clientPort);
dSocket.send(dp);
}

catch(Exception e){
e.printStackTrace(System.out);
}
}
}
class Client implements Runnable{
int index=0;
int clientPort=200;
int b_size=60;
byte[] buf=new byte[b_size];
public void run(){
try{
DatagramSocket dSocket=new DatagramSocket(clientPort);
DatagramPacket dp=new DatagramPacket(buf,b_size);
dSocket.receive(dp);
String s=new String(dp.getData(),0,dp.getLength());
System.out.println(s);
}
catch(Exception e){
e.printStackTrace(System.out);
}
}
}


------解决方案--------------------
测试过了,没发现什么问题啊,server等待输入,然后发送给client。不知道你觉得哪里没对
------解决方案--------------------
也是啊,没问题的