网络基础
来源:互联网 发布:货到付款淘宝网商城 编辑:程序博客网 时间:2024/05/01 02:40
TCP
import java.net.*;import java.io.*;public class TCPServer2{public static void main(String[]args)throws Exception{ServerSocket s=new ServerSocket(6666);while(true){Socket ss=s.accept();DataInputStream dis=new DataInputStream(ss.getInputStream());System.out.println(dis.readUTF()); //阻塞式dis.close();ss.close(); System.out.println("A client connected!");}}}
import java.net.*;import java.io.*;public class TCPClient2{public static void main(String[] args)throws Exception{Socket s=new Socket("127.0.0.1",6666);OutputStream os=s.getOutputStream();DataOutputStream dos=new DataOutputStream(os);Thread.sleep(3000);dos.writeUTF("Hello Server");dos.flush();dos.close();s.close();}}
UDP
利用UDP传递字符串:
import java.net.*;public class TestUDPServer{public static void main(String []args) throws Exception{byte buf[]=new byte[1024];DatagramPacket dp=new DatagramPacket(buf,buf.length);DatagramSocket ds=new DatagramSocket(1234);while(true){ds.receive(dp);System.out.println(new String(buf,0,dp.getLength())); //dp.getLength() !!!}}}
import java.net.*;public class TestUDPClient{public static void main(String[]args) throws Exception{byte buf[]=(new String("hello")).getBytes();DatagramPacket dp=new DatagramPacket(buf,buf.length,new InetSocketAddress("127.0.0.1",1234)); //目的主机IP和端口DatagramSocket ds=new DatagramSocket(9999); //本机端口ds.send(dp);ds.close();}}
利用UDP传递long型数值:
import java.net.*;import java.io.*;public class TestUDPServer2{public static void main(String[] args) throws Exception{ byte buf[]=new byte[1024]; DatagramPacket dp=new DatagramPacket(buf,0,buf.length);DatagramSocket ds=new DatagramSocket(1234);while(true){ds.receive(dp);ByteArrayInputStream bais=new ByteArrayInputStream(buf);DataInputStream dis=new DataInputStream(bais);System.out.println(dis.readLong());}}}
import java.net.*;import java.io.*;public class TestUDPClient2{public static void main(String[] args)throws Exception{long n=1000;ByteArrayOutputStream baos=new ByteArrayOutputStream();DataOutputStream dos=new DataOutputStream(baos);dos.writeLong(n);byte buf[]=baos.toByteArray();DatagramPacket dp=new DatagramPacket(buf,buf.length,new InetSocketAddress("127.0.0.1",1234));DatagramSocket ds=new DatagramSocket(8888);ds.send(dp);ds.close();}}
- 网络基础
- 网络基础
- 网络基础
- 网络基础
- 网络基础
- 网络基础
- 网络基础
- 网络基础
- 网络基础
- 网络基础
- 网络基础
- 网络基础
- 网络基础
- 网络基础
- 网络基础
- 网络基础
- 网络基础
- 网络基础
- iClass ipad 客户端开发总结
- 提升代码内外部质量的22条经验
- Phonegap 开发笔记
- OCP-1Z0-051-V9.02-94题
- 一直以来伴随我的一些学习习惯(四):知识结构
- 网络基础
- iOS 之按照首字母排序并赋值给相应地Section中
- iBatis整理——iBatis批处理实现(Spring环境)
- HDU1007 Quoit Design
- AIR Native Extension的使用--AIR程序中获取手机SIM卡信息
- php 正则匹配中文
- 常用排序算法总结(一)----冒泡排序,归并排序
- PLMN介绍
- windows xp下安装UbuntuKylin双系统详细步骤