<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html><head><meta http-equiv="Cont

本文涉及的产品
转发路由器TR,750小时连接 100GB跨地域
简介: 一个很基础的socket链接示例,仅用作测试和学习使用首先是服务器端的代码,一个标准的socket server,绑定本地的54321端口package online.

一个很基础的socket链接示例,仅用作测试和学习使用

首先是服务器端的代码,一个标准的socket server,绑定本地的54321端口

package online.geekgalaxy.test;


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketServer implements Runnable
{
    public void run()
    {
        try
        {
            //创建ServerSocket
            ServerSocket serverSocket = new ServerSocket(54321);
            while (true)
            {
                //接受客户端请求
                Socket client = serverSocket.accept();
                System.out.println("accept");
                try
                {
                    //接收客户端消息
                    BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
                    String str = in.readLine();
                    System.out.println("read:" + str);
                    //向服务器发送消息
                    PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(client.getOutputStream())),true);
                    out.println("server message");
                    //关闭流
                    out.close();
                    in.close();
                }
                catch (Exception e)
                {
                    System.out.println(e.getMessage());
                    e.printStackTrace();
                }
                finally
                {
                    //关闭
                    client.close();
                    System.out.println("close");
                }
            }
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
    //main函数,开启服务器
    public static void main(String a[])
    {
        Thread desktopServerThread = new Thread(new SocketServer());
        desktopServerThread.start();
    }
}

附加一个python的服务端

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import socket

s = socket.socket()
host = socket.gethostname()
port = 54321
s.bind((host, port))

s.listen(5)
while True:
    c, addr = s.accept()
    print 'Connect from ', addr
    c.send('Welcome!')
    c.close()




然后是安卓客户端,很简单,但是连接时不能使用127.0.0.1,所以使用了局域网的10段地址

manifest文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="online.geekgalaxy.socketclient">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
mainactivity文件,使用了一种不是特别推荐的方式在新的API基础上运行socket客户端命令

package online.geekgalaxy.socketclient;

import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements Runnable{

//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_main);
//    }

    private final String        DEBUG_TAG   = "MainActivity";

    private TextView    mTextView = null;
    private EditText    mEditText = null;
    private Button      mButton = null;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        mButton = (Button)findViewById(R.id.Button01);
        mTextView = (TextView)findViewById(R.id.TextView01);
        mEditText = (EditText)findViewById(R.id.EditText01);

        //登陆
        mButton.setOnClickListener(new OnClickListener()
        {
            public void onClick(View v)
            {
                run();
            }
        });
    }


        @Override
        public void run() {
            Socket socket = null;
            String message = mEditText.getText().toString() + "/r/n";
            try {
                //创建Socket
//                  socket = new Socket("192.168.1.110",54321);
                socket = new Socket("10.9.3.132", 54321); //IP:10.14.114.127,端口54321
                //向服务器发送消息
                PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
                out.println(message);

                //接收来自服务器的消息
                BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String msg = br.readLine();

                if (msg != null) {
                    mTextView.setText(msg);
                } else {
                    mTextView.setText("数据错误!");
                }
                //关闭流
                out.close();
                br.close();
                //关闭Socket
                socket.close();
            } catch (Exception e) {
                // TODO: handle exception
                Log.e(DEBUG_TAG, e.toString());
            }
        }
}

mainactivity推荐的写法,使用runnable,是上面代码的替代方案

package online.geekgalaxy.socketclient;

//import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity{

//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_main);
//    }

    private final String        DEBUG_TAG   = "MainActivity";

    private TextView    mTextView = null;
    private EditText    mEditText = null;
    private Button      mButton = null;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

//        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
//        StrictMode.setThreadPolicy(policy);

        mButton = (Button)findViewById(R.id.Button01);
        mTextView = (TextView)findViewById(R.id.TextView01);
        mEditText = (EditText)findViewById(R.id.EditText01);

        //登陆
        mButton.setOnClickListener(new OnClickListener()
        {
            public void onClick(View v)
            {
//                run();
                new Thread(runnable).start();
            }
        });
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            Socket socket;
            String message = mEditText.getText().toString() + "/r/n";
            try {
                //创建Socket
//                  socket = new Socket("192.168.1.110",54321);
                socket = new Socket("10.9.3.132", 54321); //IP:10.14.114.127,端口54321
                //向服务器发送消息
                PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
                out.println(message);

                //接收来自服务器的消息
                BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String msg = br.readLine();

                if (msg != null) {
                    mTextView.setText(msg);
                } else {
                    mTextView.setText("数据错误!");
                }
                //关闭流
                out.close();
                br.close();
                //关闭Socket
                socket.close();
            } catch (Exception e) {
                // TODO: handle exception
                Log.e(DEBUG_TAG, e.toString());
            }
        }
    };
}



然后是layout文件,里边的string被提取了出来,自己补全即可

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView
        android:id="@+id/TextView01"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/servermessage"
        />
    <EditText
        android:id="@+id/EditText01"
        android:text="@string/sendmessage"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
    </EditText>
    <Button
        android:id="@+id/Button01"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/buttonsend"
        />
</LinearLayout>
build.gradle还是贴出来吧

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.2"
    defaultConfig {
        applicationId "online.geekgalaxy.socketclient"
        minSdkVersion 25
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}









目录
相关文章
|
Web App开发 新零售 前端开发
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html><head><meta http-equiv="Cont
1.尽可能地了解需求,系统层面适用开闭原则 2.模块化,低耦合,能快速响应变化,也可以避免一个子系统的问题波及整个大系统 3.
751 0
|
Web App开发 前端开发 Java
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html><head><meta http-equiv="Cont
服务端需在vm arguments一栏下加上    -agentlib:jdwp=transport=dt_socket,server=y,address=8000 并以run模式启动 如果以debug模式启动服务端...
723 0
|
Web App开发 前端开发
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html><head><meta http-equiv="Cont
service cloudera-scm-agent stop service cloudera-scm-agent stop umount /var/run/cloudera-scm-agent/process umo...
760 0
|
Web App开发 前端开发
|
Web App开发 前端开发 Linux
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html><head><meta http-equiv="Cont
[root@hadoop058 ~]# mii-tool eth0: negotiated 100baseTx-FD, link ok 100M linux 下查看网卡工作速率 Ethtool是用于查询及设置网卡参数的命令。
648 0
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html><head><meta http-equiv="Cont
生产服务器环境最小化安装后 Centos 6.5优化配置备忘 本文 centos 6.5 优化 的项有18处,列表如下: 1、centos6.
1545 0
|
Web App开发 前端开发
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html><head><meta http-equiv="Cont
在统计分析系统中, 维度:指人们分析事物的角度。比如,分析活跃用户,可以从时间的维度,也可以从地域的维度去看,也可以时间、地域两个维度组合去分析。
667 0
|
Web App开发 前端开发
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html><head><meta http-equiv="Cont
一个典型的星型模式包括一个大型的事实表和一组逻辑上围绕这个事实表的维度表。  事实表是星型模型的核心,事实表由主键和度量数据两部分组成。
542 0

热门文章

最新文章

下一篇
无影云桌面