DatagramSocket类:
DatagramPacket类:
接收方必须先于发送方运行
import java.net.*;
public class send//发送端
{
public static void main(String [] args) throws Exception
{
DatagramSocket ds=new DatagramSocket();
String str="hello world";
DatagramPacket dp=new DatagramPacket(str.getBytes(),str.length(),
InetAddress.getByName("127.0.0.1"),3000);
System.out.println("Send: 准备发送信息");
ds.send(dp);
System.out.println("Send: 发送信息结束");
ds.close();
}
}
import java.net.*;
public class receive//接收端
{
public static void main(String[] args) throws Exception
{
DatagramSocket ds=new DatagramSocket(3000);
byte [] buf=new byte[1024];
DatagramPacket dp=new DatagramPacket(buf,1024);
System.out.println("Recv: 我在等待信息");
ds.receive(dp);//阻塞,等待发送端连接
System.out.println("Recv: 我接收到信息");
String strRecv=new String(dp.getData(),0,dp.getLength()) +
" from " + dp.getAddress().getHostAddress()+":"+dp.getPort();
ds.close();
}
}
TCP协议:有链接、保证可靠的无误差通讯:
ServerSocket:等待响应的服务器端口:
Socket:运输通道:
import java.net.*;
import java.io.*;
public class TcpServer
{
public static void main(String [] args)
{
try
{
ServerSocket ss=new ServerSocket(8001); //在001端口
Socket s=ss.accept(); //阻塞,等到有客户端Socket连接new Socket()
System.out.println("i am server");
InputStream ips=s.getInputStream(); //有人连上来,打开输入流
OutputStream ops=s.getOutputStream(); //打开输出流
ops.write("Hello, Client!".getBytes()); //输出一句话给客户端
ips.close();
ops.close();
s.close();
ss.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
import java.net.*;
import java.io.*;
public class TcpClient {
public static void main(String[] args) {
try {
Socket s = new Socket(InetAddress.getByName("127.0.0.1"), 8001); //需要服务端先开启,需要目标服务器的IO和端口
System.out.println("i am client");
InputStream ips = s.getInputStream(); //开启通道的输入流
BufferedReader br = new BufferedReader(new InputStreamReader(ips));//包装
System.out.println("Server said: " + br.readLine());//从服务端读取一句话
br.close();
s.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
原文:https://www.cnblogs.com/innndown/p/12378387.html