| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 808 人关注过本帖
标题:放两个例子,作为自己学习的纪念碑
只看楼主 加入收藏
lateraware
Rank: 1
等 级:新手上路
帖 子:36
专家分:0
注 册:2012-2-9
结帖率:66.67%
收藏
 问题点数:0 回复次数:3 
放两个例子,作为自己学习的纪念碑
TCP/Socket编程练习题:
1.客户端服务器通信
 
OneServer.java
import
import
import
import
import
import
 
 
public class OneServer {
    public static void main(String args[]) {
        ServerSocket server = null;
         
        try{
            server = new ServerSocket(12355);
            System.out.println("服务器启动:" + server.getInetAddress() + ":" + server.getLocalPort());
            
            while(true) {
                Socket socket = server.accept();
                System.out.println("客户端连接:" + socket.getInetAddress() + ":" + socket.getPort());
                 
                BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
                BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                 
                PrintWriter os = new PrintWriter(socket.getOutputStream());
                 
                String line;
                while((line = is.readLine()) != null) {
                    System.out.println("收到:" + line);
                    if(line.equals("bye")) {
                        break;
                    }
                    else {
                        os.println(sin.readLine());
                        os.flush();
                    }
                }
                 
                is.close();
                os.close();
                 
                socket.close();
            }
        }catch(IOException e) {
            e.printStackTrace();
        }finally {
            try{
                server.close();
            }catch(IOException e) {
                e.printStackTrace();
            }
        }
    }
}
 
OneClient.java
import
import
import
import
import
 
 
public class OneClient {
    public static void main(String args[]) {
        try{
            Socket socket = new Socket("localhost", 12355);
            
            BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
            
            BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            
            PrintWriter os = new PrintWriter(socket.getOutputStream());
            
            String readline;
            while((readline = sin.readLine()) != null) {
                os.println(readline);
                os.flush();
                 
                String responseline = is.readLine();
                System.out.println("收到回复:" + responseline);
            }
            
            is.close();
            os.close();
            
            socket.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}
 
2.使用多线程处理多个客户端
ManyServer.java
 
import
import
import
 
 
public class ManyServer {
    public static void main(String args[]) {
        ServerSocket server = null;
         
        try{
            server = new ServerSocket(12355);
            System.out.println("服务器启动:" + server.getInetAddress() + ":" + server.getLocalPort());
            
            while(true) {
                Socket socket = server.accept();
                System.out.println("客户端连接:" + socket.getInetAddress() + ":" + socket.getPort());
                 
                new ServerThread(socket).start();
            }
        } catch(IOException e) {
            e.printStackTrace();
        }finally {
            try{
                server.close();
            }catch(IOException e) {
                e.printStackTrace();
            }
        }
    }
}
 
ServerThread.java
import
import
import
import
import
 
 
public class ServerThread extends Thread {
    Socket socket;
     
    public ServerThread(Socket socket) {
        this.socket = socket;
    }
     
    public void run() {
        try{
            BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
            BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            
            PrintWriter os = new PrintWriter(socket.getOutputStream());
            
            String line;
            while((line = is.readLine()) != null) {
                System.out.println("收到:" + line);
                if(line.equals("bye")) {
                    break;
                }
                else {
                    os.println(sin.readLine());
                    os.flush();
                }
            }
            
            
            is.close();
            os.close();
            
            socket.close();
        }
        catch(IOException e) {
            e.printStackTrace();
        }finally {
            try{
                socket.close();
            }catch(IOException e) {
                e.printStackTrace();
            }
        }
    }
}
 
Client端的程序就是OneClient.java
 
完毕了!
 
运行截图:
[attach]75563[/attach]
[attach]75564[/attach]
 
UDP通信:
UDPServer.java
 
import
import
import
import
 
 
public class UDPServer {
    public static void main(String args[]) {
        try {
            DatagramSocket socket = new DatagramSocket(12355);
            
            byte buf[] = new byte[1200];
            DatagramPacket receivePacket = new DatagramPacket(buf, buf.length);
            System.out.println("开始接收包");
            
            while(true) {
                socket.receive(receivePacket);
                String name = receivePacket.getAddress().toString();
                System.out.println("来自主机:" + name + "\n 端口:" + receivePacket.getPort());
                 
                String s = new String(receivePacket.getData(), 0, receivePacket.getLength());
                System.out.println("接受数据:"+s);
            }
        } catch(SocketException e) {
            e.printStackTrace();
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
}
 
UDPClient.java
 
import
import
import
import
import
 
 
public class UDPClient {
    public static void main(String args[]) {
        try {
            DatagramSocket socket = new DatagramSocket();
            
            InetAddress host = InetAddress.getByName("localhost"); //InetAddress相当于一个IP的封装对象
            String msg = "hello, I'm client!";
            
            DatagramPacket sendPacket = new DatagramPacket(msg.getBytes(), msg.length(), host, 12355);
            
            socket.send(sendPacket);
        } catch(SocketException e) {
            e.printStackTrace();
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
}
[attach]75566[/attach]

UDP组播,服务器发广播的例子:

UdpSessionServer.java
import *;
import *;

public class UdpSessionServer {
    public static void main(String args[]) throws Exception {
        MulticastSocket socket = new MulticastSocket(10001);
        InetAddress group = InetAddress.getByName("239.255.8.0");
        socket.joinGroup(group);
        byte b[] = "你好,你现在收到的是我发给你的消息".getBytes();
        DatagramPacket dgPacket = new DatagramPacket(b, b.length, group, 10001);
        socket.send(dgPacket);
        socket.close();
        System.out.println("send message ok.");
    }
}

UdpSessionClient.java
import *;
import *;

public class UdpSessionClient {
    public static void main(String args[]) throws Exception {
        MulticastSocket socket = new MulticastSocket(10001);
        byte[] by = new byte[1024];
        InetAddress group = InetAddress.getByName("239.255.8.0");
        socket.joinGroup(group);
        DatagramPacket dgPacket = new DatagramPacket(by, by.length, group, 10001); // 待接收的数据包。
        socket.receive(dgPacket);
        String str = new String(by);
        System.out.println("接收到的内容:");
        System.out.println(str);
        socket.close();
    }
}
运行结果:

下面是一个多人聊天对话的demo,技术:Socket通信+多线程
1.ServerThread.java
import
import
import
import
import
import java.util.Hashtable;

public class ServerThread extends Thread{
    Socket socket;
    BufferedReader is;
    PrintWriter os;
    Hashtable<String, ServerThread> clientlist;
    String username;

    public ServerThread(Socket socket,
            Hashtable<String, ServerThread> clientlist) {
        this.socket = socket;
        this.clientlist = clientlist;

        try {
            System.out.println("try");
            is = new BufferedReader(new InputStreamReader(
                    socket.getInputStream()));
            os = new PrintWriter(socket.getOutputStream());

            this.username = is.readLine();
            clientlist.put(username, this);

            System.out.println(username + "链接:" + socket.getInetAddress() + ":"
                    + socket.getLocalPort());

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void run() {
        try {
            String line;
            while ((line = is.readLine()) != null) {
                System.out.println(username + "发给" + line);
                if (line.equals("bye"))
                    break;
                else {
                    String arr[] = line.split(":");
                    if (arr.length == 2) {
                        if (clientlist.containsKey(arr[0])) {
                            clientlist.get(arr[0]).send(username + ":" + arr[1]);
                        }
                    }
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void send(String message) {
        System.out.println("发给:" + username + " " + message);
        os.println(message);
        os.flush();
    }

}

2.ChatServer.java
import
import
import
import java.util.Hashtable;

public class ChatServer {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ServerSocket server = null;
        try {
            server = new ServerSocket(12345);
            System.out.println("服务器启动:"
                    + server.getInetAddress().getLocalHost() + ":"
                    + server.getLocalPort());

            Hashtable<String, ServerThread> clientlist = new Hashtable<String, ServerThread>();
            
            while (true) {
                System.out.println("Server Accept");
                Socket socket = server.accept();
                new ServerThread(socket, clientlist).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                server.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

3.ClientThread.java
import
import
import
import
import


public class ClientThread extends Thread{
    Socket socket;
    BufferedReader is;
    PrintWriter os;
   
    public ClientThread(String username) {
        try {
            socket = new Socket("localhost", 12345);
            
            is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            os = new PrintWriter(socket.getOutputStream());
            
            os.println(username);
            os.flush();
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
   
    public void run() {
        try {
            String readline;
            while((readline = is.readLine()) != null) {
                System.out.println(readline);
            }
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
   
    public void send(String message) {
        os.println(message);
        os.flush();
    }
   
    public void close() {
        try {
            is.close();
            os.close();
            
            socket.close();
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
}

4.ChatClient.java
import
import
import


public class ChatClient {
    public static void main(String args[]) throws Exception {
        try {
            ClientThread client = new ClientThread(args[0]);
            client.start();
            
            BufferedReader sin= new BufferedReader(new InputStreamReader(System.in));
            
            String readline;
            while((readline = sin.readLine()) != null) {
                if(readline.equals("bye")) {
                    client.close();
                    System.exit(0);
                }
                client.send(readline);
            }
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
}

运行结果:

程序结构说明:
服务器端有一个线程队列Map记录客户端的连接,每每有一客户想给另一个客户发送消息,首先该客户发送信息到服务器端,发送内容包括接受者在Map中的Key(名字username)和发送的信息内容,服务器端收到信息以后,首先查询是否存在接受者,如果存在则调用接受者对应线程的send方法把刚才那位客户发来的消息转发给他

贴不上来,运行结果不要了。

[ 本帖最后由 lateraware 于 2014-4-16 11:56 编辑 ]
搜索更多相关主题的帖子: Socket public 服务器 练习题 server 
2014-04-15 07:29
日知己所无
Rank: 11Rank: 11Rank: 11Rank: 11
等 级:贵宾
威 望:38
帖 子:427
专家分:2071
注 册:2014-3-22
收藏
得分:0 
Mark一下
2014-04-19 20:12
chenyiqing23
Rank: 2
等 级:论坛游民
帖 子:84
专家分:53
注 册:2007-12-27
收藏
得分:0 
赞 呵呵
2014-05-08 23:10
我爱敲代码
Rank: 3Rank: 3
等 级:论坛游侠
威 望:1
帖 子:70
专家分:165
注 册:2013-4-23
收藏
得分:0 
2014-05-10 00:56
快速回复:放两个例子,作为自己学习的纪念碑
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.021645 second(s), 9 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved