android 进程间通信之socket
- 使用BuffredReader ,readline获得服务器发过来的消息时,服务器发送应该采用write(msg+"\n") 然后flush;或者用PrinterWrite autoflush设置为true,然后println进行发送
public class TcpServerService extends Service { private static final String TAG = "TcpServerService"; ServerSocket serverSocket; private String[] mDefinedMessages = new String[]{ "你好啊,哈哈", "今天北京天气不错啊,shy", "你知道吗,我可是可以和多个人聊天的哦!!", "家附近哦发来句欧文!!" }; BlockingDeque blockingDeque = new LinkedBlockingDeque(); private PrintWriter printWriter; private ExecutorService executorService = new ThreadPoolExecutor(3,3,2000, TimeUnit.MICROSECONDS, blockingDeque); private boolean mIsServiceDestroyed = false; @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); executorService.submit(new TcpServer()); } class TcpServer implements Runnable{ @Override public void run() { try { /** * 绑定本地端口 */ serverSocket= new ServerSocket(1025); while (!mIsServiceDestroyed){ final Socket socket = serverSocket.accept(); Log.i(TAG, "run: accept"); executorService.submit(new Runnable() { @Override public void run() { try { responseClient(socket); } catch (IOException e) { e.printStackTrace(); } } }); } } catch (IOException e) { e.printStackTrace(); }finally { } } } private void responseClient(Socket socket) throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); // printWriter =new PrintWriter( new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true); Log.i(TAG, "欢迎来到聊天室"); while (!mIsServiceDestroyed){ String str = in.readLine(); Log.i(TAG, "Message from Client:"+str); if (str == null){ Log.i(TAG, " 客户端断开连接"); break; } int i = new Random().nextInt(mDefinedMessages.length); String msg =mDefinedMessages[i]; // printWriter.println(msg); writer.write(msg+"\n"); writer.flush(); Log.i(TAG, "send message:"+msg); } Log.i(TAG, "Client quit"); in.close(); writer.close(); socket.close(); serverSocket.close(); }
package com.lzw.cha01.myapplication.chapter2.tcp; import android.content.Intent; import android.os.Bundle; import android.os.SystemClock; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; 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 com.lzw.cha01.myapplication.R; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.Socket; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * MyApplication * Created by lzw on 2019/3/13. 13:25:47 * 邮箱:632393724@qq.com * All Rights Saved! Chongqing AnYun Tech co. LTD */ public class SocketClientActivity extends AppCompatActivity { private static final String TAG = SocketClientActivity.class.getSimpleName(); private TextView content ; private EditText et_send_conent; private Button btn_send; private Intent intent; private Socket socket; private PrintWriter mPrintWriter; private ExecutorService executorService = Executors.newCachedThreadPool(); @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout_socket_client); intent = new Intent(this,TcpServerService.class); startService(intent); connectToServer(); initView(); } @Override protected void onDestroy() { super.onDestroy(); if (socket != null){ try { socket.shutdownInput(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } stopService(intent); } private void connectToServer() { executorService.submit(new connectRunnable()); } class connectRunnable implements Runnable{ @Override public void run() { while(socket == null){ try { socket = new Socket("localhost",1025); mPrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true); } catch (IOException e) { e.printStackTrace(); SystemClock.sleep(1000); } } try { BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); while (!SocketClientActivity.this.isFinishing()){ final String str = reader.readLine(); Log.i(TAG, "Message from server:"+str); if (!TextUtils.isEmpty(str)){ runOnUiThread(new Runnable() { @Override public void run() { content.setText(content.getText() + "\n" + getCurrentTime() + "\n" + "服务端:" + str); } }); } } mPrintWriter.close(); reader.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } } private void initView() { content = findViewById(R.id.tv_content); et_send_conent = findViewById(R.id.et_send); btn_send = findViewById(R.id.btn_send); btn_send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final String sendStr = et_send_conent.getText().toString().trim(); if (TextUtils.isEmpty(sendStr)){ Toast.makeText(SocketClientActivity.this, "发送内容不能为空", Toast.LENGTH_SHORT).show(); return; } if (socket == null || mPrintWriter==null){ Toast.makeText(SocketClientActivity.this, "网络不给力", Toast.LENGTH_SHORT).show(); return; } Log.i(TAG, "onClick: "); executorService.submit(new Runnable() { @Override public void run() { mPrintWriter.println(sendStr); runOnUiThread(new Runnable() { @Override public void run() { content.setText(content.getText()+"\n"+getCurrentTime()+"\n"+"客户端:"+sendStr); et_send_conent.setText(""); } }); } }); } }); } private String getCurrentTime() { //设置日期格式 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // new Date()为获取当前系统时间 return df.format(new Date()); } }
Dana.Lee
To:Dana_Lee1016@126.com