Socket学习-Socket基础

对于一个功能齐全的Socket,都要包含以下基本结构,其工作过程包含以下四个基本的步骤:
(1) 创建Socket;
(2) 打开连接到Socket的输入/出流;
(3) 按照一定的协议对Socket进行读/写操作;
(4) 关闭Socket.


现在我们来学习学习如何一对一传输,再在一对一的基础上学习一对多的传输,学习完了之后看看如何传输一个对象~

开始我们还是来看看简单的一对一吧

服务端代码:
01 publicstatic void main(String[] args) throwsException {
02 // TODO Auto-generated method stub
03 //设定服务端的端口号
04 ServerSocket server = newServerSocket(10000);
05 //等待请求,此方法会一直阻塞,直到获得请求才往下走
06 Socket socket = server.accept();
07 //用于接收客户端发来的请求
08 BufferedReader in = newBufferedReader(newInputStreamReader(socket.getInputStream()));
09 //用于发送返回信息
10 PrintWriter out = newPrintWriter(socket.getOutputStream());
11  
12 String msg = in.readLine();
13 System.out.println(msg);
14 out.println(msg);
15 out.flush();
16  
17 socket.close();
18 }
客户端代码:
01 publicstatic void main(String[] args) throwsException {
02 //客户端socket指定服务器的地址和端口号
03 Socket socket = newSocket("localhost",10000);
04 BufferedReader in = newBufferedReader(newInputStreamReader(socket.getInputStream()));
05 PrintWriter out = newPrintWriter(socket.getOutputStream());
06 BufferedReader reader = newBufferedReader(newInputStreamReader(System.in));
07  
08 String msg = reader.readLine();
09 out.println(msg);
10 out.flush();
11 System.out.println(in.readLine());
12  
13 socket.close();
14 }
先运行服务端,然后再运行客户端,客户端控制台结果如下:
 
服务端控制台结果如下:

这样一个简单的服务端、客户端交互就完成了~
以上是一对一的交互,下面我们看看一对多的交互~
服务端代码修改如下:
01 publicstatic void main(String[] args) throwsIOException {
02 ServerSocket server = newServerSocket(10000);
03  
04 while(true) {
05 Socket socket = server.accept();
06 initSocket(socket);
07 }
08 }
09  
10 privatestatic void initSocket(finalSocket client) throwsIOException {
11 newThread(newRunnable() {
12 publicvoid run() {
13 BufferedReader in = null;
14 PrintWriter out = null;
15 try{
16 in = newBufferedReader(newInputStreamReader(client.getInputStream()));
17 out = newPrintWriter(client.getOutputStream());
18  
19 String msg = in.readLine();
20 System.out.println(msg);
21 out.println("Server received " + msg);
22 out.flush();
23  
24 }catch(IOException ex) {
25 ex.printStackTrace();
26 }finally{
27 try{
28 in.close();
29 }catch(Exception e) {}
30 try{
31 out.close();
32 }catch(Exception e) {}
33 try{
34 client.close();
35 }catch(Exception e) {}
36 }
37 }
38 }).start();
39 }
客户端代码如下(基本没变):
01 publicstatic void main(String[] args) throwsException {
02 Socket socket = newSocket("localhost",10000);
03 BufferedReader in = newBufferedReader(newInputStreamReader(socket.getInputStream()));
04 PrintWriter out = newPrintWriter(socket.getOutputStream());
05 BufferedReader reader = newBufferedReader(newInputStreamReader(System.in));
06  
07 String msg = reader.readLine();
08 out.println(msg);
09 out.flush();
10 System.out.println(in.readLine());
11  
12 socket.close();
13 }
运行服务端,运行客户端后,客户端可以运行多个,第一个客户端结果如下:
 
第二个客户端结果如下:
 
服务端结果如下:
 

这样就实现了一对多的通信~

以上客户端与服务端传输的都是一个字符串,在实际应用中我们不可能传输这样一个简单的字符串,我们还可能传一个对象等等。
现在我们来学习一下如何传一个对象。
服务端代码如下:
01 publicstatic void main(String[] args) throwsIOException {
02 ServerSocket server = newServerSocket(10000);
03  
04 while(true) {
05 Socket socket = server.accept();
06 initSocket(socket);
07 }
08 }
09  
10 privatestatic void initSocket(finalSocket socket) throwsIOException {
11 newThread(newRunnable() {
12 publicvoid run() {
13 ObjectInputStream is = null;
14 ObjectOutputStream os = null;
15 try{
16 is = newObjectInputStream(newBufferedInputStream(socket.getInputStream()));
17 os = newObjectOutputStream(socket.getOutputStream());
18  
19 Object obj = is.readObject();
20 User user = (User)obj;
21 System.out.println("user: " + user.getName() + "/"+ user.getPassword());
22  
23 user.setName(user.getName() + "_new");
24 user.setPassword(user.getPassword() + "_new");
25  
26 os.writeObject(user);
27 os.flush();
28 }catch(IOException ex) {
29 logger.log(Level.SEVERE,null, ex);
30 }catch(ClassNotFoundException ex) {
31 logger.log(Level.SEVERE,null, ex);
32 }finally{
33 try{
34 is.close();
35 }catch(Exception ex) {}
36 try{
37 os.close();
38 }catch(Exception ex) {}
39 try{
40 socket.close();
41 }catch(Exception ex) {}
42 }
43 }
44 }).start();
45 }
客户端代码如下:
01 publicstatic void main(String[] args) throwsException {
02 Socket socket = null;
03 ObjectOutputStream os = null;
04 ObjectInputStream is = null;
05  
06 try{
07 socket = newSocket("localhost",10000);
08  
09 os = newObjectOutputStream(socket.getOutputStream());
10 User user = newUser("user","password");
11 os.writeObject(user);
12 os.flush();
13  
14 is = newObjectInputStream(newBufferedInputStream(socket.getInputStream()));
15 Object obj = is.readObject();
16 if(obj != null) {
17 user = (User)obj;
18 System.out.println("user: " + user.getName() + "/"+ user.getPassword());
19 }
20 }catch(IOException ex) {
21 logger.log(Level.SEVERE,null, ex);
22 }finally{
23 try{
24 is.close();
25 }catch(Exception ex) {}
26 try{
27 os.close();
28 }catch(Exception ex) {}
29 try{
30 socket.close();
31 }catch(Exception ex) {}
32 }
33 }
当然在客户端和服务端都需要一个对象User,代码如下:
01 publicclass User implementsjava.io.Serializable {
02 privatestatic final long serialVersionUID = 1L;
03 privateString name;
04 privateString password;
05  
06 publicUser() {
07  
08 }
09  
10 publicUser(String name, String password) {
11 this.name = name;
12 this.password = password;
13 }
14  
15 publicString getName() {
16 returnname;
17 }
18  
19 publicvoid setName(String name) {
20 this.name = name;
21 }
22  
23 publicString getPassword() {
24 returnpassword;
25 }
26  
27 publicvoid setPassword(String password) {
28 this.password = password;
29 }
30 }
运行服务端客户端...
服务端接收客户端的对象结果:
 
客户端接收服务端返回的对象结果:
 

这样我们就实现了传输对象~

转自:http://bbs.51cto.com/thread-1084435-1.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值