DatagramSocket ds = new DatagramSocket(); byte[] by = “hello,udp”.getBytes(); DatagramPacket dp = new DatagramPacket(by,0,by.length, InetAddress.getByName(“127.0.0.1”),10000); ds.send(dp); ds.close();
DatagramSocket ds = new DatagramSocket(10000); byte[] by = new byte[1024]; DatagramPacket dp = new DatagramPacket(by,by.length); ds.receive(dp); String str = new String(dp.getData(),0,dp.getLength()); System.out.println(str+"--"+dp.getAddress()); ds.close();
Socket s = new Socket(“192.168.1.1”,9999); OutputStream out = s.getOutputStream(); out.write(“hello”.getBytes()); s.close();
ServerSocket ss = new ServerSocket(9999); Socket s = ss.accept (); InputStream in = s.getInputStream(); byte[] buf = new byte[1024]; int num = in.read(buf); String str = new String(buf,0,num); System.out.println(s.getInetAddress().toString()+”:”+str); s.close(); ss.close();
UDP和TCP区别:
Socket()
通过系统默认类型的 SocketImpl 创建未连接套接字Socket(InetAddress address, int port)
创建一个流套接字并将其连接到指定 IP 地址的指定端口号。Socket(String host, int port,InetAddress localAddr,
int localPort)
创建一个套接字并将其连接到指定远程主机上的指定远程端口。 bind(SocketAddress bindpoint)
将套接字绑定到本地地址。close()
关闭此套接字。connect(SocketAddress endpoint)
将此套接字连接到服务器。connect(SocketAddress endpoint, int timeout)
将此套接字连接到服务器,并指定一个超时值。getInetAddress()
返回套接字连接的地址。getLocalAddress()
获取套接字绑定的本地地址。getPort()
返回此套接字连接到的远程端口。isClosed()
返回套接字的关闭状态。isConnected()
返回套接字的连接状态。toString()
将此套接字转换为String
。package server; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String[] args) throws IOException { /* * 自定义server 服务端 * 获取浏览器的信息。并反馈信息。 */ System.out.println("my server run...."); ServerSocket ss = new ServerSocket(9090); Socket s = ss.accept(); System.out.println(s.getInetAddress().getHostAddress()+"....connected"); //读取客户端的数据。 InputStream in = s.getInputStream(); byte[] buf = new byte[1024]; int len = in.read(buf); String text = new String(buf,0,len-1); System.out.println(text); //给客户端回馈数据。 PrintWriter out = new PrintWriter(s.getOutputStream(),true); out.println("<font color='red' size='7'>欢迎光临</font>"); s.close(); ss.close(); } }
原文地址:http://blog.csdn.net/u013233097/article/details/46398199