Socket 通信
IP地址的组成 32位 由4个8位二进制数组成。
IP=网络地址+主机地址
Ipconfig/all dos命令查看ip
测试网络是否连通
Ping 127.0.0.0(本机地址)看自己的网卡有没有坏
Ping www.baidu.com 看能不能连上广域网
服务器:性能很好的计算机
端口号:每一个程序都会有一个唯一的端口号,程序之间端口号不能一样
Nextline() 一次一行
//服务器
package 客户端一来一回;import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.util.Scanner;public class send {public static void main(String[] args) {// TODO Auto-generated method stubString con = "";do {try {Scanner input = new Scanner(System.in);byte[] buf = new byte[1024];DatagramPacket dp = new DatagramPacket(buf, buf.length);System.out.println("服务端已启动,等待客户端连接..");//创建datagramsocket对象,接收数据DatagramSocket ds = new DatagramSocket(8800);ds.receive(dp);//显示接收到的信息String mess = new String(dp.getData(), 0, dp.getLength());System.out.println(dp.getAddress().getHostAddress() + "说:"+ mess);System.out.println("服务器你好,请输入你的内容");String reply = input.nextLine();System.out.println("同学b 说:" + reply);// 创建datagramPacket对象,封装数据SocketAddress sa = dp.getSocketAddress();DatagramPacket dpto = new DatagramPacket(reply.getBytes(),reply.getBytes().length, sa);ds.send(dpto);ds.close();con = reply;} catch (SocketException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}} while (!con.equals("bye"));}}
//客户端
package 客户端一来一回;import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;public class Receive {public static void main(String[] args) {// TODO Auto-generated method stubString con="";do{try {Scanner input=new Scanner(System.in);System.out.println("客户端你好,请输入你的内容");String mess=input.nextLine();System.out.println("同学a 说:"+mess);//获取本地主机地址InetAddress ia=InetAddress.getByName("localhost");// 创建datagramPacket对象,封装数据DatagramPacket dp=new DatagramPacket(mess.getBytes(), mess.getBytes().length,ia,8800);//创建datagramsocket对象,向服务器发送数据DatagramSocket ds=new DatagramSocket();ds.send(dp);byte[] buf=new byte[1024];DatagramPacket dpre=new DatagramPacket(buf, buf.length);//创建datagramsocket对象,接收数据ds.receive(dpre);String reply=new String(dpre.getData(),0,dpre.getLength());System.out.println("同学b 说:"+reply);ds.close();con=mess;} catch (UnknownHostException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (SocketException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}while(!con.equals("bye"));}}