客户端使用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
- 客户端使用Socket与服务器通信
- C# 使用Socket实现服务器与客户端的通信
- Android客户端通过socket与服务器通信
- Java Socket编程(服务器与客户端通信)
- Android客户端通过socket与服务器通信
- Android客户端通过socket与服务器通信
- python服务器与android客户端socket通信
- Android客户端通过socket与服务器通信
- Android客户端通过socket与服务器通信
- Android客户端通过socket与服务器通信
- Android客户端通过socket与服务器通信
- Android客户端与本地服务器Socket通信
- socket实现服务器与客户端通信
- android客户端与服务器socket通信实例
- 使用C语言socket实现windows pc与ftp服务器通信---socket实现ftp客户端
- C# Socket通信的服务器与客户端的通信
- Android客户端通过socket与服务器通信(解决源码使用出现的错误)
- tcp通讯的方式并使用socket建立客户端与服务器的通信的过程
- 读Log文件,当文件大小变化时打开文件,从新添加的几行读
- TC SRM 683 div2 MoveStonesEasy 贪心
- DSB,ISB,DMB指令
- UVA Find the Permutations 11077 (DP&置换群)
- 各位有谁知道COEP这表是干什么的吗?
- 客户端使用Socket与服务器通信
- C#如何使用异步编程
- 线程池ThreadPoolExecutor使用简介
- Mysql/SQLServer数据类型与java基本数据类型的对应
- 统计学知识
- Web报表工具FineReport实现EXCEL数据导入自由报表
- Leetcode(6) - easy
- ASP.NET常被忽视的一些细节
- NET平台开源JSON库LitJSON的使用方法