客户端使用Socket与服务器通信

来源:互联网 发布:网络空间安全期刊 编辑:程序博客网 时间:2024/06/09 22:23

安卓端代码

1.主界面MainActivity.java

package com.gst.user.myapplication;import android.os.AsyncTask;import android.os.Bundle;import android.support.design.widget.FloatingActionButton;import android.support.design.widget.Snackbar;import android.support.v7.app.AppCompatActivity;import android.support.v7.widget.Toolbar;import android.view.View;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.net.Socket;public class MainActivity extends AppCompatActivity{    EditText editTextIp;    EditText editTextContent;    TextView textView;    Socket socket;    BufferedReader reader;    BufferedWriter writer;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_voice_recognize);        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);        setSupportActionBar(toolbar);        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);        fab.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)                        .setAction("Action", null).show();            }        });        editTextIp=(EditText)findViewById(R.id.editText);        editTextContent=(EditText)findViewById(R.id.editText2);        textView=(TextView)findViewById(R.id.textView);    }    public void onClickConnect(View view){        AsyncTask<Void,String,Void> connect=new AsyncTask<Void, String, Void>() {            String dstName;            int dstPort;            @Override            protected Void doInBackground(Void... params) {                try {                    socket=new Socket(dstName,dstPort);                    reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));                    writer=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));                    publishProgress("@success");                    String line=null;                    while ((line=reader.readLine())!=null){                        publishProgress(line);                    }                } catch (IOException e) {                    Toast.makeText(VoiceRecognizeActivity.this,"无法到服务器",Toast.LENGTH_SHORT).show();                    e.printStackTrace();                }                return null;            }            @Override            protected void onProgressUpdate(String... values) {                if (values[0].equals("@success")){                    Toast.makeText(VoiceRecognizeActivity.this,"成功连接到服务器",Toast.LENGTH_SHORT).show();                }                textView.append("别人说:"+values[0]+"\n");                super.onProgressUpdate(values);            }            @Override            protected void onPreExecute() {                dstName="192.168.42.30";                dstPort=6666;                super.onPreExecute();            }        };        connect.execute();    }    public void onClickSend(View view){        if (writer==null){            return;        }        try {            textView.append("我说:"+editTextContent.getText().toString()+"\n");            writer.write(editTextContent.getText().toString()+"\n");            writer.flush();            editTextContent.setText("");        } catch (IOException e) {            e.printStackTrace();        }    }}
2.布局文件activity_voice_recognize.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    android:paddingBottom="@dimen/activity_vertical_margin"    app:layout_behavior="@string/appbar_scrolling_view_behavior"    tools:showIn="@layout/activity_voice_recognize"    tools:context="com.gst.user.myapplication.VoiceRecognizeActivity">    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="连接到主机"        android:id="@+id/button"        android:onClick="onClickConnect"        android:layout_alignParentTop="true"        android:layout_alignParentEnd="true" />    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="发送"        android:onClick="onClickSend"        android:id="@+id/button2"        android:layout_alignParentBottom="true"        android:layout_centerHorizontal="true"        android:layout_marginBottom="49dp" />    <EditText        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:id="@+id/editText"        android:layout_alignBottom="@+id/button"        android:layout_alignParentStart="true" />    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:textAppearance="?android:attr/textAppearanceMedium"        android:id="@+id/textView"        android:layout_marginTop="44dp"        android:layout_below="@+id/editText"        android:layout_alignParentStart="true" />    <EditText        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:id="@+id/editText2"        android:layout_above="@+id/button2"        android:layout_toStartOf="@+id/button"        android:layout_alignEnd="@+id/button" /></RelativeLayout>

电脑服务器端

ServerListener.java

import java.io.IOException;import java.net.ServerSocket;import java.net.Socket;import javax.swing.JOptionPane;public class ServerListener extends Thread {@Overridepublic void run() {//1-65535try {ServerSocket serverSocket = new ServerSocket(6666);while (true) {//blockSocket socket = serverSocket.accept();//建立连接JOptionPane.showMessageDialog(null, "有客户端链接到了本机的12345端口");//将socket传递给新的线程ChatSocket cs = new ChatSocket(socket);cs.start();ChatManager.getChatManager().add(cs);}} catch (IOException e) {e.printStackTrace();}}}

ChatSocket.java

import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.io.UnsupportedEncodingException;import java.net.Socket;public class ChatSocket extends Thread {Socket socket;public ChatSocket(Socket s){this.socket = s;}public void out(String out) {try {socket.getOutputStream().write((out+"\n").getBytes("UTF-8"));} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}@Overridepublic void run() {out("你已经连接到本服务器了");try {BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"));String line = null;while ((line = br.readLine()) != null) {System.out.println(line);ChatManager.getChatManager().publish(this, line);}br.close();} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
3.ChatManager.java
import java.util.Vector;public class ChatManager {private ChatManager(){}private static final ChatManager cm = new ChatManager();public static ChatManager getChatManager() {return cm;}Vector<ChatSocket> vector = new Vector<ChatSocket>();public void add(ChatSocket cs) {vector.add(cs);}public void publish(ChatSocket cs,String out) {for (int i = 0; i < vector.size(); i++) {ChatSocket csChatSocket = vector.get(i);if (!cs.equals(csChatSocket)) {csChatSocket.out(out);}}}}
4.MyServerSocket.java
public class MyServerSocket {public static void main(String[] args) {new ServerListener().start();}}

0 0