TCP双向通讯

TCP双向通讯

实现双向通讯

双向通讯服务器:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
* 服务器(双向):
* 1.指定端口,使用ServerSocket创建服务器
* 2.阻塞式等待链接 accept 返回一个Socket
* 3.操作:输入输出流
* 4.释放资源
*/
public class TCP_TwoWayServer {
public static void main(String[] args) throws Exception {
System.out.println("-------Server-------");
//1.指定端口,使用ServerSocket创建服务器
ServerSocket SS=new ServerSocket(6666);
// 2.阻塞式等待链接 accept
Socket Client=SS.accept();
System.out.println("客户端连接已建立");
// 3.操作:输入输出流
DataInputStream dis=new DataInputStream(Client.getInputStream());
String st=dis.readUTF();
String[] data =st.split("&");
String name="";
String pwd="";
for(String b:data ) {
String[] c=b.split("=");
if(c[0].equals("name")) {
//System.out.println("用户名是:"+c[1]);
name=c[1];
}
else {
//System.out.println("密码是:"+c[1]);
pwd=c[1];
}
}
DataOutputStream out=new DataOutputStream(Client.getOutputStream());
if(name.equals("123")&&pwd.equals("456")) {
out.writeUTF("登陆成功");
}
else {
out.writeUTF("用户名或密码错误");
}
// 4.释放资源
dis.close();
Client.close();
}
}

双向通讯客户端:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* 客户端(双向):
* 1.建立连接:使用Socket创建客户端:服务器地址和端口
* 2.操作:输入输出流
* 3.释放资源
*/
public class TCP_TwoWayClient {
public static void main(String[] args) throws Exception {
System.out.println("-------Client-------");
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
System.out.println("请输入姓名:");
String name=bf.readLine();
System.out.println("请输入密码:");
String pwd=bf.readLine();
//1.建立连接:使用Socket创建客户端:服务器地址和端口
Socket S=new Socket("localhost",6666);
// 3.操作:输入输出流
DataOutputStream out=new DataOutputStream(S.getOutputStream());
out.writeUTF("name="+name+"&"+"pwd="+pwd);
out.flush();
DataInputStream dis=new DataInputStream(S.getInputStream());
String sss=dis.readUTF();
System.out.println(sss);
// 4.释放资源
out.close();
S.close();
}
}

结果:

——-Server——-
客户端连接已建立

——-Client——-
请输入姓名:
123
请输入密码:
123
用户名或密码错误

原创技术分享,您的支持将鼓励我继续创作
0%