首页 > 代码库 > 初识Socket通信:基于TCP和UDP协议学习网络编程

初识Socket通信:基于TCP和UDP协议学习网络编程

学习笔记:

1.基于TCP协议的Socket网络编程:

  (1)Socket类构造方法:在客户端和服务器端建立连接

    Socket s = new Socket(hostName,port);以主机名和端口号作为参数来创建一个Socket对象。

    Socket s = new Socket(address,port);以InetAddress对象和端口号作为参数来创建一个Socket对象。

  创建Socket对象时可能抛出UnknownHostException或IOException异常,必须捕获它们。

  (2)常用方法

    InetAddress getInetAddress();返回与Socket对象关联的InetAddress

    int getPort();远程端口

    int getLocalPort();本地端口

    InputStream getInputStream();相关联的InputStream

    OutputStream getOutputStream();相关联的OutputStream

    void close();关闭该Socket

 

  (3)ServerSocket类:等待客户端建立连接,连接以后进行通信

    ServerSocket ss = new ServerSocket(port);接收端口号作为参数

    ServerSocket ss = new ServerSocket(port,maxqueue);接收端口号和最大队列长度作为参数。

 

    accept();等待客户端触发通信

 1 import java.io.BufferedReader;
 2 import java.io.IOException;
 3 import java.io.InputStream;
 4 import java.io.InputStreamReader;
 5 import java.io.OutputStream;
 6 import java.net.ServerSocket;
 7 import java.net.Socket;
 8 
 9 /**
10  * 使用Socket变成实现用户登录
11  * 1.实现单用户登录
12  * 2.服务器端关键代码
13  * @author Administrator
14  *
15  */
16 public class Test0101 {
17 
18     public static void main(String[] args) {
19         try {
20             //创建一个服务器Socket(ServerSocket),指定端口8800并开始监听
21             ServerSocket serverSocket = new ServerSocket(8800);
22             //使用accept()方法等待客户端触发通信
23             Socket socket = serverSocket.accept();
24             //打开输入/输出流
25             InputStream is = socket.getInputStream();
26             OutputStream os = socket.getOutputStream();
27             //获取客户端信息,即从输入流读取信息
28             BufferedReader br = new BufferedReader(new InputStreamReader(is));
29             String info = null;
30             while(!((info = br.readLine())==null)){
31                 System.out.println("我是服务器,客户登录信息为:"+info);
32             }
33             socket.shutdownInput();
34             //给客户端一个响应,即向输出流写入信息
35             String reply = "欢迎你,登陆成功!";
36             os.write(reply.getBytes());
37             os.close();
38             br.close();
39             is.close();
40             socket.close();
41             serverSocket.close();
42         } catch (IOException e) {
43             e.printStackTrace();
44         }
45     }
46 
47 }
 1 import java.io.BufferedReader;
 2 import java.io.IOException;
 3 import java.io.InputStream;
 4 import java.io.InputStreamReader;
 5 import java.io.OutputStream;
 6 import java.net.Socket;
 7 import java.net.UnknownHostException;
 8 
 9 /**
10  * 使用Socket变成实现用户登录
11  * 1.实现单用户登录
12  * 2.客户端关键代码
13  * @author Administrator
14  *
15  */
16 public class Test01 {
17 
18     public static void main(String[] args) {
19         try {
20             //建立客户端Socket连接,指定服务器的位置为本机以及端口8800
21             Socket socket = new Socket("127.0.0.1",8800);
22             //打开输入/输出流
23             OutputStream os = socket.getOutputStream();
24             InputStream is = socket.getInputStream();
25             //发送客户端登录信息,即向输出流写入信息
26             String info = "用户名:Tom;用户密码:123456";
27             os.write(info.getBytes());
28             socket.shutdownOutput();
29             //接受服务器端的响应,即从输入流读取信息
30             String reply = null;
31             BufferedReader br = new BufferedReader(new InputStreamReader(is));
32             while(!((reply = br.readLine())==null)){
33                 System.out.println("我是客户端,服务器端的响应为:"+reply);
34             }
35             //关闭资源
36             br.close();
37             is.close();
38             os.close();
39             socket.close();
40         } catch (UnknownHostException e) {
41             e.printStackTrace();
42         } catch (IOException e) {
43             e.printStackTrace();
44         }
45         
46     }
47 
48 }
 1 import java.io.IOException;
 2 import java.io.InputStream;
 3 import java.io.ObjectInputStream;
 4 import java.io.OutputStream;
 5 import java.net.ServerSocket;
 6 import java.net.Socket;
 7 
 8 /**
 9  * 服务器端关键代码
10  * @author Administrator
11  *
12  */
13 public class Test0201 {
14 
15     public static void main(String[] args) {
16         try {
17             //创建一个服务器Socket(ServerSocket)连接,指定端口并开始监听
18             ServerSocket serverSocket = new ServerSocket(8800);
19             //使用accpet()方法等待客户端触发通信
20             Socket socket = serverSocket.accept();
21             //打开输入输出流
22             InputStream is = socket.getInputStream();
23             OutputStream os = socket.getOutputStream();
24             //反序列化
25             ObjectInputStream ois = new ObjectInputStream(is);
26             //获取客户端信息(从输入流读取信息)
27             User user = (User)ois.readObject();
28             if (!(user==null)) {
29                 System.out.println("我是服务器端,客户登录信息为:\n用户名:"+user.getLoginName()+",密码:"+user.getPwd());
30             }
31             //给客户端一个响应(向输出流写入信息)
32             String reply = "欢迎你,登陆成功!";
33             os.write(reply.getBytes());
34             //关闭资源
35             os.close();
36             ois.close();
37             is.close();
38             socket.close();
39             serverSocket.close();
40         } catch (ClassNotFoundException e) {
41             e.printStackTrace();
42         } catch (IOException e) {
43             e.printStackTrace();
44         }
45 
46     }
47 
48 }
 1 import java.io.BufferedReader;
 2 import java.io.IOException;
 3 import java.io.InputStream;
 4 import java.io.InputStreamReader;
 5 import java.io.ObjectOutputStream;
 6 import java.io.OutputStream;
 7 import java.net.Socket;
 8 import java.net.UnknownHostException;
 9 
10 /**
11  * 客户端关键代码
12  * @author Administrator
13  *
14  */
15 public class Test02 {
16 
17     public static void main(String[] args) {
18         try {
19             //建立客户端Socket连接,指定服务器的位置和端口
20             Socket socket = new Socket("127.0.0.1",8800);
21             //打开输入输出流
22             OutputStream os = socket.getOutputStream();
23             InputStream is = socket.getInputStream();
24             //对象序列化
25             ObjectOutputStream oos = new ObjectOutputStream(os);
26             //发送客户端登录信息(向输出流写入数据)
27             User user = new User();
28             user.setLoginName("Tom");
29             user.setPwd("12345678");
30             oos.writeObject(user);
31             socket.shutdownOutput();
32             //接收服务器端的响应(从输入流读取信息)
33             String reply = null;
34             BufferedReader br = new BufferedReader(new InputStreamReader(is));
35             while(!((reply = br.readLine())==null)){
36                 System.out.println("我是客户端,服务器端的响应为"+reply);
37             }
38             //关闭资源
39             br.close();
40             oos.close();
41             is.close();
42             os.close();
43             socket.close();
44         } catch (UnknownHostException e) {
45             e.printStackTrace();
46         } catch (IOException e) {
47             e.printStackTrace();
48         }
49 
50     }
51 
52 }

案例:实现多客户端用户登录

1.登录线程类

 1 import java.io.IOException;
 2 import java.io.InputStream;
 3 import java.io.ObjectInputStream;
 4 import java.io.OutputStream;
 5 import java.net.Socket;
 6 
 7 /**
 8  * 登录线程类
 9  * @author Administrator
10  *
11  */
12 public class LoginThread extends Thread {
13     Socket socket = null;
14     //每启动一个线程,连接对应的Socket接口
15     public LoginThread(Socket socket){
16         this.socket = socket;
17     }
18     //启动线程,即响应客户请求
19     public void run(){
20         try {
21             //打开输入输出流
22             InputStream is = socket.getInputStream();
23             OutputStream os = socket.getOutputStream();
24             //反序列化
25             ObjectInputStream ois = new ObjectInputStream(is);
26             //获取客户端信息(从输入流读取信息)
27             User user = (User)ois.readObject();
28             if (!(user==null)) {
29                 System.out.println("我是服务器端,客户登录信息为:\n用户名:"+user.getLoginName()+",密码:"+user.getPwd());
30             }
31             //给客户端一个响应(向输出流写入信息)
32             String reply = "欢迎你,登陆成功!";
33             os.write(reply.getBytes());
34             //关闭资源
35             os.close();
36             ois.close();
37             is.close();
38             socket.close();
39         } catch (ClassNotFoundException e) {
40             e.printStackTrace();
41         } catch (IOException e) {
42             e.printStackTrace();
43         }
44     }
45 
46 }

2.服务器端的响应

 1 import java.io.IOException;
 2 import java.net.ServerSocket;
 3 import java.net.Socket;
 4 
 5 /**
 6  * 服务器端关键代码
 7  * @author Administrator
 8  *
 9  */
10 public class Test0301 {
11 
12     public static void main(String[] args) {
13         try {
14             //创建一个服务器Socket(ServerSocket),指定端口并开始监听
15             @SuppressWarnings("resource")
16             ServerSocket serverSocket = new ServerSocket(8800);
17             //使用accpet()方法等待客户端触发通信
18             Socket socket = null;
19             while (true) {
20                 //监听一直进行中
21                 socket = serverSocket.accept();
22                 LoginThread login = new LoginThread(socket);
23                 login.start();
24             }
25         } catch (IOException e) {
26             e.printStackTrace();
27         }
28 
29     }
30 
31 }

3.客户登陆

 1 import java.io.BufferedReader;
 2 import java.io.IOException;
 3 import java.io.InputStream;
 4 import java.io.InputStreamReader;
 5 import java.io.ObjectOutputStream;
 6 import java.io.OutputStream;
 7 import java.net.Socket;
 8 import java.net.UnknownHostException;
 9 
10 /**
11  * 实现多客户端用户登录
12  * @author Administrator
13  *
14  */
15 public class Test03 {
16 
17     public static void main(String[] args) {
18         try {
19             //建立客户端Socket连接,指定服务器的位置和端口
20             Socket socket = new Socket("127.0.0.1",8800);
21             //打开输入输出流
22             OutputStream os = socket.getOutputStream();
23             InputStream is = socket.getInputStream();
24             //对象序列化
25             ObjectOutputStream oos = new ObjectOutputStream(os);
26             //发送客户端登录信息(向输出流写入数据)
27             User user = new User();
28             user.setLoginName("Kate");
29             user.setPwd("12345678");
30             oos.writeObject(user);
31             socket.shutdownOutput();
32             //接收服务器端的响应(从输入流读取信息)
33             String reply = null;
34             BufferedReader br = new BufferedReader(new InputStreamReader(is));
35             while(!((reply = br.readLine())==null)){
36                 System.out.println("我是客户端,服务器端的响应为"+reply);
37             }
38             //关闭资源
39             br.close();
40             oos.close();
41             is.close();
42             os.close();
43             socket.close();
44         } catch (UnknownHostException e) {
45             e.printStackTrace();
46         } catch (IOException e) {
47             e.printStackTrace();
48         }
49     }
50 
51 }

二、InetAddress类中的工厂方法

  static InetAddress getLocalHost();返回本地主机InetAddress对象

  static InetAddress getByName(String hostName);返回InetAddress对象

  static InetAddress[] getAllByName(String hostName);返回主机名~所有主机对象组

 1 import java.net.InetAddress;
 2 import java.net.UnknownHostException;
 3 
 4 /**
 5  * 获取淘宝网服务器地址
 6  * @author Administrator
 7  *
 8  */
 9 public class Test002 {
10 
11     public static void main(String[] args) {
12         //定义目标网址
13         String target = "localhost";
14         System.out.println("------淘宝的主服务器地址------");
15         InetAddress iad;
16         try {
17             iad = InetAddress.getByName(target);
18             System.out.println(iad);
19         } catch (UnknownHostException e) {
20             e.printStackTrace();
21         }
22         
23         System.out.println("------淘宝的所有服务器地址------");
24         InetAddress[] iads;
25         try {
26             iads = InetAddress.getAllByName(target);
27             System.out.println(target+"的IP地址有"+iads.length+"个,分别是:");
28             for (InetAddress ia : iads) {
29                 System.out.println(ia);
30             }
31         } catch (UnknownHostException e) {
32             e.printStackTrace();
33         }
34 
35     }
36 
37 }

 

初识Socket通信:基于TCP和UDP协议学习网络编程