安卓应用开发Socket通信 客户端+服务器端

1. 添加网络权限

<uses-permission android:name="android.permission.INTERNET" />

2. 布局代码

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity"><Buttonandroid:id="@+id/connect"android:layout_width="104dp"android:layout_height="48dp"android:layout_marginTop="84dp"android:layout_marginEnd="6dp"android:text="连接"app:backgroundTint="#940327ED"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintTop_toTopOf="parent" /><Buttonandroid:id="@+id/send"android:layout_width="102dp"android:layout_height="50dp"android:layout_marginTop="150dp"android:layout_marginEnd="6dp"android:text="发送"app:backgroundTint="#850027FF"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintTop_toTopOf="parent" /><EditTextandroid:id="@+id/send_text"android:layout_width="291dp"android:layout_height="57dp"android:layout_marginStart="2dp"android:layout_marginTop="144dp"android:ems="10"android:inputType="textPersonName"android:text="聊天内容"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toTopOf="parent" /><EditTextandroid:id="@+id/tcp_ip"android:layout_width="181dp"android:layout_height="56dp"android:layout_marginStart="2dp"android:layout_marginTop="76dp"android:ems="10"android:inputType="textPersonName"android:text="192.168.1.1"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toTopOf="parent" /><EditTextandroid:id="@+id/tcp_port"android:layout_width="91dp"android:layout_height="56dp"android:layout_marginTop="76dp"android:layout_marginEnd="128dp"android:ems="10"android:inputType="number"android:text="8700"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintTop_toTopOf="parent" /><TextViewandroid:id="@+id/Recv_text"android:layout_width="match_parent"android:layout_height="251dp"android:layout_marginStart="2dp"android:layout_marginEnd="2dp"android:layout_marginBottom="240dp"android:background="#811B99D3"android:text="聊天内容"android:textAlignment="center"android:textColor="#D900FF"android:textSize="16sp"android:textStyle="bold"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintHorizontal_bias="0.0"app:layout_constraintStart_toStartOf="parent" /><TextViewandroid:id="@+id/textView"android:layout_width="152dp"android:layout_height="38dp"android:layout_marginTop="16dp"android:layout_marginEnd="140dp"android:text="客户端"android:textAlignment="center"android:textSize="24sp"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintTop_toTopOf="parent" /></androidx.constraintlayout.widget.ConstraintLayout>

3. 主代码

  1. 声明控件
    private EditText tcp_port;//端口private EditText tcp_ip;//ip地址public TextView sendtext;//发送文本private TextView  Recv_text;//接收文本private ConnectThread connectThread;//声明连接内部类
  1. 绑定控件
        Button connect=findViewById(R.id.connect);Button send=findViewById(R.id.send);tcp_port=findViewById(R.id.tcp_port);tcp_ip=findViewById(R.id.tcp_ip);Recv_text=findViewById(R.id.Recv_text);sendtext=findViewById(R.id.send_text);
  1. 完整代码
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;public class MainActivity extends AppCompatActivity {private EditText tcp_port;private EditText tcp_ip;public TextView sendtext;private TextView  Recv_text;private ConnectThread connectThread;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Button connect=findViewById(R.id.connect);connect.setText("连接");Button send=findViewById(R.id.send);tcp_port=findViewById(R.id.tcp_port);tcp_ip=findViewById(R.id.tcp_ip);Recv_text=findViewById(R.id.Recv_text);sendtext=findViewById(R.id.send_text);connect.setOnClickListener(new View.OnClickListener() {public void onClick(View v) {connectThread = new ConnectThread();connectThread.start();connect.setText("已连接");connect.setBackgroundColor(Color.parseColor("#00ff00"));}});send.setOnClickListener(new View.OnClickListener() {public void onClick(View v) {//发送数据if (connectThread.socket != null) {new Thread(new Runnable() {@Overridepublic void run() {try {connectThread.outputStream.write(sendtext.getText().toString().getBytes());} catch (IOException e) {e.printStackTrace();}}}).start();}}});}class ConnectThread extends Thread {Socket socket = null;        //定义socketOutputStream outputStream = null;    //定义输出流(发送)InputStream inputStream = null;    //定义输入流(接收)public void run() {try {//用InetAddress方法获取ip地址InetAddress ipAddress = InetAddress.getByName(tcp_ip.getText().toString());int port = Integer.valueOf(tcp_port.getText().toString());        //获取端口号socket = new Socket(ipAddress, port);Log.e("Socket", socket.toString());//连接失败if (null == socket) {runOnUiThread(new Runnable() {@Overridepublic void run() {Toast.makeText(getApplicationContext(), "连接失败", Toast.LENGTH_SHORT).show();}});return;}//获取输出流outputStream = socket.getOutputStream();//接收数据while (true) {final byte[] buffer = new byte[1024];//创建接收缓冲区inputStream = socket.getInputStream();final int len = inputStream.read(buffer);//数据读出来,并且返回数据的长度if (len != 0) {runOnUiThread(new Runnable() {@Overridepublic void run() {Recv_text.setText("");Recv_text.append(new String(buffer, 0, len) + "\r\n");}});}}} catch (IOException e) {e.printStackTrace();}}}
}


1. 添加网络权限

<uses-permission android:name="android.permission.INTERNET" />

2. 布局代码

 <Buttonandroid:id="@+id/listen"android:layout_width="104dp"android:layout_height="48dp"android:layout_marginTop="84dp"android:layout_marginEnd="6dp"android:text="开始监听"app:backgroundTint="#940327ED"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintTop_toTopOf="parent" /><Buttonandroid:id="@+id/send"android:layout_width="102dp"android:layout_height="50dp"android:layout_marginTop="150dp"android:layout_marginEnd="6dp"android:text="发送"app:backgroundTint="#850027FF"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintTop_toTopOf="parent" /><EditTextandroid:id="@+id/send_text"android:layout_width="291dp"android:layout_height="57dp"android:layout_marginStart="2dp"android:layout_marginTop="144dp"android:ems="10"android:inputType="textPersonName"android:text="聊天内容"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toTopOf="parent" /><EditTextandroid:id="@+id/tcp_port"android:layout_width="91dp"android:layout_height="56dp"android:layout_marginTop="76dp"android:layout_marginEnd="128dp"android:ems="10"android:inputType="number"android:text="8700"android:textSize="20sp"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintTop_toTopOf="parent" /><TextViewandroid:id="@+id/Recv_text"android:layout_width="match_parent"android:layout_height="251dp"android:layout_marginStart="2dp"android:layout_marginEnd="2dp"android:layout_marginBottom="188dp"android:background="#811B99D3"android:text="聊天内容"android:textAlignment="center"android:textColor="#D900FF"android:textSize="16sp"android:textStyle="bold"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintHorizontal_bias="1.0"app:layout_constraintStart_toStartOf="parent" /><TextViewandroid:id="@+id/textView"android:layout_width="152dp"android:layout_height="38dp"android:layout_marginTop="16dp"android:layout_marginEnd="140dp"android:text="服务器端"android:textAlignment="center"android:textSize="24sp"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintTop_toTopOf="parent" /><TextViewandroid:id="@+id/textView2"android:layout_width="171dp"android:layout_height="47dp"android:layout_marginTop="84dp"android:layout_marginEnd="16dp"android:text="设置端口:"android:textSize="24sp"android:textStyle="bold"app:layout_constraintEnd_toStartOf="@+id/tcp_port"app:layout_constraintTop_toTopOf="parent" />

3. 主代码

  1. 声明控件
    private EditText tcp_port;//端口public TextView sendtext;//发送文本private TextView  Recv_text;//接收文本private ConnectThread listenThread;//声明监听内部类
  1. 绑定控件
        Button listen=findViewById(R.id.listen);listen.setText("开启监听");Button send=findViewById(R.id.send);tcp_port=findViewById(R.id.tcp_port);Recv_text=findViewById(R.id.Recv_text);sendtext=findViewById(R.id.send_text);
  1. 完整代码
import androidx.appcompat.app.AppCompatActivity;import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;public class MainActivity extends AppCompatActivity {private EditText tcp_port;public TextView sendtext;private TextView  Recv_text;private  ListenTheard listenTheard;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Button listen=findViewById(R.id.listen);listen.setText("开启监听");Button send=findViewById(R.id.send);tcp_port=findViewById(R.id.tcp_port);Recv_text=findViewById(R.id.Recv_text);sendtext=findViewById(R.id.send_text);listen.setOnClickListener(new View.OnClickListener() {public void onClick(View v) {listenTheard = new ListenTheard();listenTheard.start();listen.setText("已打开监听");listen.setBackgroundColor(Color.parseColor("#00ff00"));}});send.setOnClickListener(new View.OnClickListener() {public void onClick(View v) {//发送数据if (listenTheard.socket != null) {new Thread(new Runnable() {@Overridepublic void run() {try {listenTheard.outputStream.write(sendtext.getText().toString().getBytes());} catch (IOException e) {e.printStackTrace();}}}).start();}}});}class ListenTheard extends Thread{ServerSocket socket = null;OutputStream outputStream;InputStream in;public void run(){try{int port=Integer.valueOf(tcp_port.getText().toString());socket=new ServerSocket(port);Socket s=socket.accept();outputStream=s.getOutputStream();while(true){final byte[] buffer = new byte[1024];//创建接收缓冲区in=s.getInputStream();final int len = in.read(buffer);//数据读出来,并且返回数据的长度String S=new String(buffer,0,len);String[] D=S.split(",");if (len != 0) {runOnUiThread(new Runnable() {@Overridepublic void run() {Recv_text.setText("");Recv_text.append(new String(buffer,0,len));}});}}}catch (Exception e){e.printStackTrace();}}}}

各位精英,这里就是基础的网络通信,不喜欢可以不看,不要喷哈,有问题私信我

安卓应用开发Socket通信 客户端+服务器端相关推荐

  1. java客户端服务器代码_Java Socket通信 客户端服务器端基本代码

    [服务器端] import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import ...

  2. C#+Socket 聊天室(实现公网通信 客户端-服务器端-客户端)

    文章目录 简述 功能演示视频(b站) 准备工作 服务器端 服务器端界面 服务器端代码 客户端 客户端界面 客户端代码 总结 简述 关于Socket的原理我就不在这里赘述了,有大佬已经作详细的说明了: ...

  3. java socket通信 客户端_JavaのSocket编程之简单客户端与服务器端通信

    Socket编程之简单客户端与服务器端通信 socket 通常用来实现客户端和服务端的连接,socket 是Tcp/Ip协议的一个十分流行的编程界面,一个socket 由一个Ip地址和一个端口号唯一确 ...

  4. 关于Socket通信客户端是否需要绑定端口号

    参见http://blog.chinaunix.net/uid-23193900-id-3199173.html 无连接的socket的客户端和服务端以及面向连接socket的服务端通过调用bind函 ...

  5. Java中Socket通信-客户端与服务端相互传输对象数据

    场景 Java中Socket通信-服务端和客户端双向传输字符串实现: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/1084885 ...

  6. Java中Socket通信-客户端向服务端发送照片

    场景 Java中Socket通信-服务端和客户端双向传输字符串实现: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/1084885 ...

  7. Socket通信客户端报错Connection reset

    Socket服务端启动不报错,在启动客户端后控制台出现如下问题 [ Exception in thread "main" java.net.SocketException: Con ...

  8. C++ socket 通信客户端和服务器端

                 #include <iostream> #include <stdio.h> #include <windows.h> //一定要包含 ...

  9. Socket通信 客户端加密数据,传递数据密文到服务端,服务端解密密文 输出明文

    server // sdf_cpp_warpper.cpp : 此文件包含 "main" 函数.程序执行将在此处开始并结束. // server端#ifndef UNICODE # ...

最新文章

  1. 是的,网络身份证来了!一堆技术和安全上的麻烦事也来了
  2. Apache Tuscany 宣布停止维护
  3. 安装node,vue编译环境
  4. [Bug] .NET 2.0 的Bug —— ComboBox中不能添加Component.
  5. c语言结构体赋值,并输出各种类型变量的值
  6. linux网络编程之用一张图片说明套接口常用函数
  7. 深度剖析开源分布式监控CAT
  8. p1和p7签名的区别
  9. 用数据来证明累计充值赠送活动
  10. 【JavaScript】AJAX总结(异步JavaScript和XML)
  11. mysql-------视图
  12. 《Head First》 MVC运用的设计模式
  13. Pwn入门之ELF文件
  14. 基于ASP的高校宿舍管理系统设计与实现
  15. 人体的基本五行 - 心肝脾肺肾,金木水火土 对应关系与基础解读
  16. 使用lgtm发现开源项目安全漏洞
  17. Xilinx VIVADO 中 DDR3(AXI4)的使用(3)模块封装
  18. 怎样查看计算机历史的开机时间,win10系统怎么查看电脑的历史开关机时间|win10系统如何查询电脑开机后运行多长时间...
  19. 微商城分销系统开发方式需求与价格开发周期评估
  20. 10 大话设计模式C++实现之模板方法模式

热门文章

  1. 教材订购模块java代码实现_基于jsp的高校教材征订-JavaEE实现高校教材征订 - java项目源码...
  2. sass、scss、css、less
  3. python调用阿里云sdk入门(hello world)
  4. 中科院自动化研究所彭思龙:科学家创业的“七宗罪”
  5. 找女朋友 SDUT(2109)
  6. Monthly Expense(二分专题)
  7. TCP/IP详解之环回接口(loopback interface)
  8. Elasticsearch实战(十五)---查询query,filter过滤,结合aggs 进行局部/全局聚合统计
  9. 二叉树:先序遍历,中序遍历,后序遍历,层序/层次遍历
  10. java 内存模型面试_Java面试- JVM 内存模型讲解