UDP
public class UdpSendDemo {
public static void main(String[] args) throws IOException {
DatagramSocket ds = new DatagramSocket();
byte[] bytes = "hellp,upd,我来了".getBytes();
int len = bytes.length;
InetAddress address = InetAddress.getByName("localhost");
DatagramPacket dp = new DatagramPacket(bytes,len, address,8888);
ds.send(dp);
ds.close();
}
}
public class UdpReceiveDemo {
public static void main(String[] args) throws IOException {
DatagramSocket ds = new DatagramSocket(8888);
byte[] bytes = new byte[1024];
DatagramPacket dp = new DatagramPacket(bytes,bytes.length);
ds.receive(dp);
System.out.println(new String(dp.getData(),0,dp.getLength()));
ds.close();
}
}
TCP
public class Client {
public static void main(String[] args) throws IOException {
Socket s = new Socket("localhost",8888);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
String line;
while((line = br.readLine()) != null){
if(line.equals("886")){
break;
}
bw.write(line);
bw.newLine();
bw.flush();
}
s.close();
}
}
public class server {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(8888);
Socket s = ss.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
String line;
while((line = br.readLine()) != null){
System.out.println(new String(line));
}
ss.close();
}
}