|
最近在学Java网络通讯,做毕业设计,我想使用UDP协议,今天写了一个C/S通讯,但服务器收不到发送出去的数据。
程序如下,Server端:
- import java.net.DatagramSocket;
- import java.net.SocketException;
- import java.nio.channels.DatagramChannel;
- import java.net.*;
- import java.io.*;
- import java.nio.*;
- public class STest {
- public static void main(String args[]){
- new Server();
- }
- }
- class Server{
- private DatagramChannel channel;
- DatagramSocket socket;
- public Server(){
- try{
- channel=DatagramChannel.open();
- socket=channel.socket();
- socket.bind(new InetSocketAddress(5569));
- SThread s=new SThread(channel);
- s.start();
- }catch(SocketException e){
- e.printStackTrace();
- }catch(IOException e){
- e.printStackTrace();
- }
- }
- }
- class SThread extends Thread{
- private DatagramChannel socket;
- public SThread(DatagramChannel socket){
- this.socket=socket;
- }
- public void run(){
- ByteBuffer buf=ByteBuffer.allocate(3000);
- while(true){
- buf.clear();
- try{
- socket.receive(buf);
- if(buf.limit()==0){
- System.out.println("Empty buf");
- continue;
- }
- buf.flip();
- System.out.println(buf.getInt());
- }catch(IOException e){
- e.printStackTrace();
- }
- }
- }
- }
复制代码
Client端
- import java.net.*;
- import java.nio.*;
- import java.nio.channels.DatagramChannel;
- import java.io.*;
- public class CTest {
- public static void main(String args[]){
- try{
- new Client().start();
- Thread.sleep(1000);
- }catch(InterruptedException e){
-
- }
- }
- }
- class Client extends Thread{
- public Client(){
- }
- public void run(){
- while(true){
- ByteBuffer buf=ByteBuffer.allocate(3000);
- buf.flip();
- try{
- DatagramChannel dc=DatagramChannel.open();
- InetSocketAddress ad=new InetSocketAddress("localhost",5569);
- dc.connect(ad);
- dc.socket().setSoTimeout(1000);
- buf.putInt(33559900);
- int out=dc.write(buf);
- this.sleep(1000);
- }catch(IOException e){
- e.printStackTrace();
- }catch(InterruptedException e){
- e.printStackTrace();
- }
- }
- }
- }
复制代码
当客户端发送数据后,服务器端收到的总是空的ByteBuffer
谁能给我一个有关DatagramChannel的服务器端和客户端的正确的例子?
还有一问,为什么linuxsir越来越慢了。。。。。:ask |
|