java學(xué)習(xí)

          java學(xué)習(xí)

           

          java網(wǎng)絡(luò)編程中tcp和udp

          在網(wǎng)絡(luò)編程中,先啟動(dòng)service,再啟動(dòng)clent。
          1.tcp
          服務(wù)端
          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通信,是不區(qū)分客戶端和服務(wù)端的
          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) 評(píng)論(0)  編輯  收藏


          只有注冊(cè)用戶登錄后才能發(fā)表評(píng)論。


          網(wǎng)站導(dǎo)航:
           

          導(dǎo)航

          統(tǒng)計(jì)

          常用鏈接

          留言簿

          隨筆檔案

          搜索

          最新評(píng)論

          閱讀排行榜

          評(píng)論排行榜

          主站蜘蛛池模板: 金昌市| 临邑县| 邯郸县| 沙雅县| 隆林| 乐亭县| 平舆县| 镇巴县| 蚌埠市| 富川| 长寿区| 德格县| 咸阳市| 贵定县| 麟游县| 黔西| 清苑县| 南昌市| 象山县| 河曲县| 绥化市| 阿拉尔市| 肥乡县| 佛坪县| 平果县| 兴城市| 天镇县| 洛南县| 临沂市| 四子王旗| 巴青县| 磐安县| 达州市| 达拉特旗| 乃东县| 漳浦县| 德格县| 富源县| 大兴区| 张北县| 长岛县|