Socket 与ServerScoket用法简介(TCP)
Posted li1234567980
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Socket 与ServerScoket用法简介(TCP)相关的知识,希望对你有一定的参考价值。
1 import java.io.BufferedReader;
2 import java.io.IOException;
3 import java.io.InputStreamReader;
4 import java.io.PrintWriter;
5 import java.net.Socket;
6
7 public class ClientText
8
9 public static void main(String[] args) throws IOException
10 //创建客户端socket对象
11 //Socket s = new Socket(InetAddress.getLocalHost(), 8888);
12 //127.0.0.1表示IP 8888表示端口号
13 Socket s = new Socket("127.0.0.1", 8888);
14
15 //获取用户名和密码
16 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
17 System.out.println("请输入用户名:");
18 String username = br.readLine();
19 System.out.println("请输入密码:");
20 String password = br.readLine();
21
22 //获取输出流对象
23 //BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
24 PrintWriter out = new PrintWriter(s.getOutputStream(), true);
25
26 //写出数据
27 out.println(username);
28 out.println(password);
29
30 //获取输入流对象
31 BufferedReader bur = new BufferedReader(new InputStreamReader(s.getInputStream()));
32
33 //获取返回的数据
34 String result = bur.readLine();
35 System.out.println(result);
36
37 //释放资源
38 s.close();
39
40
1 import java.io.BufferedReader;
2 import java.io.IOException;
3 import java.io.InputStreamReader;
4 import java.io.PrintWriter;
5 import java.net.ServerSocket;
6 import java.net.Socket;
7 import java.util.List;
8
9 public class ServerText
10
11 public static void main(String[] args) throws IOException
12 //创建ServerSocket对象
13 ServerSocket ss = new ServerSocket(8888);
14
15 //监听
16 Socket s = ss.accept();
17
18 //获取输入流对象
19 BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
20
21 //获取用户名和密码
22 String username = br.readLine();
23 String password = br.readLine();
24
25 //判断是否正确
26 boolean flag = false;
27 List<User> users = UserDB.getUers();
28 User user = new User(username, password);
29 if(users.contains(user))
30 flag = true;
31
32 PrintWriter out = new PrintWriter(s.getOutputStream(), true);
33
34 //返回判断结果
35 if (flag)
36 out.println("登录成功");
37 else
38 out.println("登录失败");
39
40 //释放资源
41 s.close();
42
43
以上是关于Socket 与ServerScoket用法简介(TCP)的主要内容,如果未能解决你的问题,请参考以下文章