java學習

          java學習

           

          java網絡編程中tcp和udp

          在網絡編程中,先啟動service,再啟動clent。
          1.tcp
          服務端
          public class Service {
          public static void main(String[] args) throws Exception {
          ServerSocket ss = new ServerSocket(6666);
          System.out.println("等待");
          while (true) {
          Socket socket  =ss.accept();
          InputStream is = socket.getInputStream();
          DataInputStream dataInputStream = new DataInputStream(is);
          System.out.println(dataInputStream.readUTF());
          dataInputStream.close();
          socket.close();
          }
          }
          }
          客戶端
          public class CientSocket {
          public static void main(String[] args) throws Exception {
          Socket socket = new Socket("127.0.0.1",6666);
          OutputStream outputStream = socket.getOutputStream();
          DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
          dataOutputStream.writeUTF("333333333");
          dataOutputStream.flush();
          dataOutputStream.close();
          socket.close();
          }
          }
          udp通信,是不區分客戶端和服務端的
          public class Service {
          public static void main(String[] args) throws Exception {
          byte buf[] = new byte[1024];
          DatagramPacket dPacket = new DatagramPacket(buf, buf.length);
          DatagramSocket dSocket = new DatagramSocket(5678);
          while (true) {
          dSocket.receive(dPacket);
          System.out.println(new String(buf,0,dPacket.getLength()));
          }
          }
          }
          public class UdpClient {
          public static void main(String[] args) throws Exception{
          while (true) {
          byte[] buf = (new String("hello")).getBytes();
          DatagramPacket dpPacket = new DatagramPacket(buf, buf.length, new InetSocketAddress("127.0.0.1", 5678));
          //自己占用9999端口
          DatagramSocket dSocket = new DatagramSocket(9999);
          dSocket.send(dpPacket);
          dSocket.close();
          }
          }
          }

          posted on 2013-04-02 22:28 楊軍威 閱讀(170) 評論(0)  編輯  收藏


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           

          導航

          統計

          常用鏈接

          留言簿

          隨筆檔案

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 崇文区| 延寿县| 准格尔旗| 布拖县| 道真| 隆回县| 抚州市| 酒泉市| 芜湖县| 克山县| 平安县| 山阴县| 绥滨县| 安溪县| 盱眙县| 包头市| 浑源县| 牟定县| 合川市| 绥江县| 瑞丽市| 商洛市| 南靖县| 平谷区| 蓝山县| 萝北县| 峨眉山市| 临安市| 岳普湖县| 亚东县| 靖宇县| 香港| 堆龙德庆县| 额尔古纳市| 四会市| 江源县| 漠河县| 宿松县| 绥江县| 乃东县| 扶绥县|