1.使用UDP协议编写一个网络程序,设置接收端程序的监听端口是8001,发送端发送的数据是“Hello,world”。
package test;
import java.net.*;
public class example01 {
public static void main(String[] args) throws Exception{
byte[] buf = new byte[1024];
DatagramSocket ds = new DatagramSocket(8001);
DatagramPacket dp = new DatagramPacket (buf,1024);
System.out.println("等待接收数据");
ds.receive(dp);
String str = new String(dp.getData(),0,dp.getLength()) ;
System.out.println(str);
ds.close();
}
}
package test;
import java.net.*;
public class example02 {
public static void main(String[] args) throws Exception{
DatagramSocket ds = new DatagramSocket(3000);
String str = "Hello, world";
DatagramPacket dp = new DatagramPacket (str.getBytes(),str.length(),
InetAddress.getByName("localhost"),8001);
System.out.println("发送信息");
ds.send(dp);
ds.close();
}
}
2.使用TCP协议编写一个网络程序,设置服务器端的监听端口是8002,当与客户端建立连接后,服务器端向客户端发送数据“Hello,world”,客户端收到数据后打印输出。
package test;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPServer {
public static void main(String[] args) throws Exception {
{
// TODO Auto-generated method stub
ServerSocket ss = new ServerSocket(8881);
while (true) {
Socket s = ss.accept();
// System.out.println("A client connect");
// DataInputStream dis = new
// DataInputStream(s.getInputStream());//数据输入流
// System.out.println(dis.readUTF());//输出读取的信息
// dis.close();
OutputStream os = s.getOutputStream();// 输出流
DataOutputStream dos = new DataOutputStream(os);// 数据输出流
dos.writeUTF("Hello Server!");// 想文本写出流
dos.flush();//
s.close();
}
}
}
}
[java] view plain copy
package test;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.OutputStream;
import java.net.Socket;
public class TCPCliant {
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
Socket s = new Socket("127.0.0.1", 8881);
DataInputStream dis = new DataInputStream(s.getInputStream());//数据输入流(二合一)
System.out.println(dis.readUTF());//输出读取的信息
dis.close();
//OutputStream os = s.getOutputStream();//输出流
//DataOutputStream dos= new DataOutputStream(os);//数据输出流
//dos.writeUTF("Hello Server!");//想文本写出流
//dos.flush();//
// dos.close();
s.close();
}
}