Socket通常也称做”套接字“,用于描述IP地址和端口,废话不多说,它就是网络通信过程中端点的抽象表示。值得一提的是,Java在包java.net中提供了两个类Socket和ServerSocket,分别用来表示双向连接的客户端和服务端。这是两个封装得非常好的类,使用起来很方便!

下面将首先创建一个SocketServer的类作为服务端如下,该服务端实现了多线程机制,可以在特定端口处监听多个客户请求,一旦有客户请求,Server总是会创建一个服务纯种来服务新来的客户,而自己继续监听。程序中accept()是一个阻塞函数,所谓阻塞性方法就是说该方法被调用后将等待客户的请求,直到有一个客户启动并请求连接到相同的端口,然后accept()返回一个对应于客户的Socket。这时,客户方和服务方都建立了用于通信的Socket,接下来就是由各个Socket分别打开各自的输入、输出流。

  • SocketServer类,服务器实现:

 1 package HA.Socket;
2
3 import java.io.*;
4 import java.net.*;
5
6  public class SocketServer {
7
8 ServerSocket sever;
9
10 public SocketServer(int port){
11 try{
12 sever = new ServerSocket(port);
13 }catch(IOException e){
14 e.printStackTrace();
15 }
16 }
17
18 public void beginListen(){
19 while(true){
20 try{
21 final Socket socket = sever.accept();
22
23 new Thread(new Runnable(){
24 public void run(){
25 BufferedReader in;
26 try{
27 in = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"));
28 PrintWriter out = new PrintWriter(socket.getOutputStream());
29 while (!socket.isClosed()){
30 String str;
31 str = in.readLine();
32 out.println("Hello!world!! " + str);
33 out.flush();
34 if (str == null || str.equals("end"))
35 break;
36 System.out.println(str);
37 }
38 socket.close();
39 }catch(IOException e){
40 e.printStackTrace();
41 }
42 }
43 }).start();
44 }catch(IOException e){
45 e.printStackTrace();
46 }
47 }
48 }
49 }
  • SocketClient类,客户端实现:

 1 package HA.Socket;
2
3 import java.io.*;
4 import java.net.*;
5
6  public class SocketClient {
7 static Socket client;
8
9 public SocketClient(String site, int port){
10 try{
11 client = new Socket(site,port);
12 System.out.println("Client is created! site:"+site+" port:"+port);
13 }catch (UnknownHostException e){
14 e.printStackTrace();
15 }catch (IOException e){
16 e.printStackTrace();
17 }
18 }
19
20 public String sendMsg(String msg){
21 try{
22 BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
23 PrintWriter out = new PrintWriter(client.getOutputStream());
24 out.println(msg);
25 out.flush();
26 return in.readLine();
27 }catch(IOException e){
28 e.printStackTrace();
29 }
30 return "";
31 }
32 public void closeSocket(){
33 try{
34 client.close();
35 }catch(IOException e){
36 e.printStackTrace();
37 }
38 }
39 public static void main(String[] args) throws Exception{
40
41 }
42
43 }

接下来就是来测试Socket通信了!

先运行TestSocketServer类,打开服务端,在12345端口处监听!


1 package HA.Socket;
2
3  public class TestSocketServer {
4
5 public static void main(String[] argvs){
6 SocketServer server = new SocketServer(12345);
7 server.beginListen();
8 }
9 }

再运行TestSocketClient类:


 1 package HA.Socket;
2
3  public class TestSocketClient {
4
5 public static void main(String[] args){
6
7 SocketClient client = new SocketClient("127.0.0.1",12345);
8 System.out.println(client.sendMsg("nimei1"));
9 client.closeSocket();
10
11 SocketClient client1 = new SocketClient("127.0.0.1",12345);
12 System.out.println(client1.sendMsg("nimei1111"));
13 client1.closeSocket();
14
15 SocketClient client11 = new SocketClient("127.0.0.1",12345);
16 System.out.println(client11.sendMsg("nimei11111111"));
17 client11.closeSocket();
18
19 SocketClient client111 = new SocketClient("127.0.0.1",12345);
20 System.out.println(client111.sendMsg("nimei11111111111111111"));
21 client111.closeSocket();
22
23 }
24 }

输出结果如下:

服务端:


Client is created! site:127.0.0.1 port:12345
Hello!world!! nimei1
Client is created! site:127.0.0.1 port:12345
Hello!world!! nimei1111
Client is created! site:127.0.0.1 port:12345
Hello!world!! nimei11111111
Client is created! site:127.0.0.1 port:12345
Hello!world!! nimei11111111111111111

客户端:

nimei1
nimei1111
nimei11111111
nimei11111111111111111
 
 
标签: android

【android】Socket简单用法的更多相关文章

  1. Android AsyncTask 简单用法

    简介 AsyncTask 是一个轻量级的异步处理类.使用是需继承自该类.可以方便的执行异步任务并且在将进度显示在UI上. 注意事项 AsyncTask只适合处理轻量级的任务即耗时几秒或者几十秒的任务. ...

  2. Android Scroller简单用法

    Android里Scroller类是为了实现View平滑滚动的一个Helper类.通常在自定义的View时使用,在View中定义一个私有成员mScroller = new Scroller(conte ...

  3. Android intent-filter 简单用法

    对电话拨号盘的过滤,mainfest配置文件中Activity如下配置: <activity Android:name=".TestActivity" android:lab ...

  4. Android Scroller简单用法实例

    Android里Scroller类是为了实现View平滑滚动的一个Helper 类.通常在自定义的View时使用,在View中定义一个私有成员mScroller = new Scroller(cont ...

  5. Android Scroller简单用法 --View滚动

    转:http://ipjmc.iteye.com/blog/1615828 Android里Scroller类是为了实现View平滑滚动的一个Helper类.通常在自定义的View时使用,在View中 ...

  6. Android MultiType第三方库的基本使用和案例+DiffUtil的简单用法

    1.MultiType简单介绍 1.1.MultiType用于比较复杂的页面. 如下图,今日头条用到了MultiType处理各种复杂的页面.    这种还是比较简单的类型.因为一个页面也就这种类型. ...

  7. Android—— ListView 的简单用法及定制ListView界面

    一.ListView的简单用法 2. 训练目标 1) 掌握 ListView 控件的使用 2) 掌握 Adapter 桥梁的作用 实现步骤: 1)首先新建一个项目, 并让ADT 自动帮我们创建好活动. ...

  8. Android Spinner的简单用法。

    今天学到的是spinner,就是下拉列表,这可不是ExpandListView哈. 闲话不解释.这是控件,所以先上布局:就不上线性布局了,基本上可以总结出,控件都得在布局里写,写之前嵌个布局就行. & ...

  9. Android之Adapter用法总结-(转)

    Android之Adapter用法总结 1.概念 Adapter是连接后端数据和前端显示的适配器接口,是数据和UI(View)之间一个重要的纽带.在常见的View(List View,Grid Vie ...

随机推荐

  1. windows技巧--一次关闭所有资源管理器目录,文件夹目录

    每天开机工作一段时间以后,你可能会和我一样,打开了很多的文件目录,于是一个一个的点窗口关闭.于是想有没有一次关闭所有目录的办法~~咚咚咚,经过一番寻觅,下面是我找到的办法 新建bat文件 close_ ...

  2. Linux系统运行级别配置

    Linux的运行级别 Linux的运行级别有七种,可以通过查看/etc/inittab文件进行了解: Level0:系统停机状态,默认系统运行级别不能设置为0,否则系统不能正常启动: Level1:单 ...

  3. skynet 创建存储过程脚本

    最近主程更改了数据库的操作方案,由之前的拼写sql脚本转为在mysql端创建好存储过程后,直接调用存储过程. 首先对一个表测试上述过程: 数据库端存储过程:(测试表) CREATE TABLE `ra ...

  4. linux ioctl()函数

    我这里说的ioctl函数是指驱动程序里的,因为我不知道还有没有别的场合用到了它,所以就规定了我们讨论的范围.写这篇文章是因为我前一阵子被ioctl给搞混了,这几天才弄明白它,于是在这里清理一下头脑. ...

  5. VIM操作基础命令

    VIM操作基础命令 1 文件操作 1.1 打开文件 VIM 使用 –o 或 –O 选项打开多个文件,其中 –o 表示垂直并排,例如 vim -o lesson4 lesson5 lesson6.大O表 ...

  6. Juniper

    Juniper Networks[编辑]     Juniper Networks 公司类型 上市(NYSE:JNPR) 成立 1996年2月 代表人物 执行长:Shaygan Kheradpir技术 ...

  7. day5-随机数相关:random模块&string模块

    一.概述 随机数在程序设计中的属于比较基础的内容,主要用于验证场景(如验证码,生成账号对应的密码等),今天结合random模块和string模块来谈谈python中随机数那些事儿. 二.随机数实现相关 ...

  8. New Concept English three (38)

    26w/m 45 Future historians will be in a unique position when they come to record the history of our ...

  9. Juint 单元测试(1)

    Junit 是一个基于Java语言的回归单元测试框架.是白盒测试的一种技术,记住这些就可以了. 为项目添加Junit 1 右键项目名称选择“Properties”,在弹出的窗体中选择“Java Bui ...

  10. 《Scala入坑笔记》缘起 3天就搞了一个 hello world

    有小伙伴向我咨询 play framework 的问题,我就想了解一下 play framework ,按照官方的文档,要使用 SBT 安装,就掉进了 SBT 的坑. 第一坑:国外仓库太慢 安装完成后 ...