TCP:需要经历“三次握手”建立连接后,发送数据
客户端:
public class ClientSocket {
public static void main(String[] args) throws Exception {
Socket so = new Socket("localhost", 88);
// 创建Socket用户,第一个参数为本地IP,第二个参数为目的端口
System.out.println("请输入");
BufferedReader b1 = new BufferedReader(new InputStreamReader(System.in));
String passwd = b1.readLine();
// 获取从控制台输入的信息
PrintStream p = new PrintStream(so.getOutputStream());
// 创建输出对象
p.println(passwd);
p.flush();
// 输出passwd
BufferedReader b2 = new BufferedReader(new InputStreamReader(
so.getInputStream()));
String r = b2.readLine();
// 获取服务返回的数据
System.out.println(r);
so.close();
// 释放资源
}
}
服务端:
public class SocketServer {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(88);
// 创建Socket服务,注意服务的端口号
Socket so = ss.accept();
// 服务接收到的信息
BufferedReader b = new BufferedReader(new InputStreamReader(
so.getInputStream()));
String passwd = b.readLine();
// 读取并获取信息
String response;
if (passwd.equals("ZWQ")) {
response = "有效口令";
} else {
response = "无效口令";
}
PrintStream p = new PrintStream(so.getOutputStream());
p.println(response);
// 返回信息
so.close();
ss.close();
// 释放资源
}
}
UDP:不需要建立连接,直接发送
客户端:
public class DatagramClient {
static DatagramSocket ds;
static byte[] buffer;
public static void main(String[] args) throws Exception {
ds = new DatagramSocket(8080);
// 创建一个8080端口的DatagramSocket,注意与服务端的DatagramSocket端口号不能相同
System.out.println("客户机正在等待服务器发送数据");
buffer = new byte[1024];
while (true) {
DatagramPacket p = new DatagramPacket(buffer, buffer.length);
ds.receive(p);
//接收数据
String psx = new String(p.getData(), 0, p.getLength());
//数据类型转换
System.out.println(psx);
if (psx.equals("end"))
break;
}
System.out.println("客户机退出运行");
}
}
服务端:
public class DatagramServer {
static DatagramSocket ds;
public static void main(String[] args) throws Exception {
byte[] buffer = new byte[1024];
ds = new DatagramSocket(8081);
// 创建一个8081端口的DatagramSocket,注意与客户端的DatagramSocket端口号不能相同
BufferedReader dis = new BufferedReader(
new InputStreamReader(System.in));
// 从控制台输入
System.out.println("服务器正在等待输入");
InetAddress ia = InetAddress.getByName("localhost");
// 获取IP
while (true) {
String str = dis.readLine();
// 获取控制台输入的数据
buffer = str.getBytes();
ds.send(new DatagramPacket(buffer, str.length(), ia, 8080));
// 把buffer发送给端口为8080的DatagramSocket
if (str == null || str.equals("end")) {
break;
}
}
System.out.println("服务器退出运行");
}
}
注意:
需要客户端和服务端都在运行状态才能测试;
TCP代码测试的时候要先运行服务端然后再运行客户端,直接运行客户端会报错,UDP可随意顺序运行;
测试过程中最常见的错误就是端口号冲突,如果发生这样的情况就重启编程工具;
切换控制台(多个程序同时运行):
点击控制台中红框中的窗口切换或者点击红框中的倒三角选择哪一个窗口