个人练习代码库Socket聊天客户端

xiaoxiao2021-02-28  6

 MainAc

import android.content.Intent; import android.os.Build; import android.os.Handler; import android.os.Message; import android.os.SystemClock; import android.support.annotation.RequiresApi; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Scroller; import android.widget.TextView; import java.io.BufferedOutputStream; 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; public class MainActivity extends AppCompatActivity { private static final int MESSAGE_RECEIVE_NEW_MSG=1; private static final int MESSAGE_SOCKET_CONNECTED=2; private static final String TAG="TCPAc"; private TextView tv; private EditText et; private Button button; private PrintWriter printWriter; private Socket clientSocket; private Handler mHandler=new Handler(new Handler.Callback() { @Override public boolean handleMessage(Message msg) { switch (msg.what){ case MESSAGE_RECEIVE_NEW_MSG: tv.setText(tv.getText()+(String)msg.obj); break; case MESSAGE_SOCKET_CONNECTED: button.setEnabled(true); break; default: break; } return false; } }); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button=findViewById(R.id.button); et=findViewById(R.id.editText); tv=findViewById(R.id.text); Intent intent=new Intent(MainActivity.this,MyService.class); startService(intent); new Thread(new Runnable() { @Override public void run() { connectTCPService(); } }).start(); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final String etText=et.getText().toString(); if (!etText.isEmpty()&&printWriter!=null) { new Thread(new Runnable() { @Override public void run() { printWriter.println(etText); } }).start(); et.setText(""); String time = SimpleDateFormat.getTimeInstance().format(System.currentTimeMillis()); final String showedMsg = "self" + time + ":" + etText + "\n"; tv.setText(tv.getText() + showedMsg); } } }); } @Override protected void onDestroy() { if (clientSocket!=null){ try { clientSocket.shutdownInput(); clientSocket.close(); } catch (IOException e) { e.printStackTrace(); } } super.onDestroy(); } private void connectTCPService() { Socket socket=null; while (socket==null){ try { socket=new Socket("localhost",8688); clientSocket=socket; printWriter=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true); mHandler.sendEmptyMessage(MESSAGE_SOCKET_CONNECTED); Log.e(TAG,"success"); } catch (IOException e) { SystemClock.sleep(1000); Log.e(TAG,"failed"); } } //接收服务端的消息 try { BufferedReader bufferedReader=new BufferedReader( new InputStreamReader(socket.getInputStream())); while (!MainActivity.this.isFinishing()){ String str=bufferedReader.readLine(); if (str!=null){ String time=SimpleDateFormat.getTimeInstance().format(System.currentTimeMillis()); final String showedMsg="server"+time+":"+str+"\n"; Message message=new Message(); message.what=MESSAGE_RECEIVE_NEW_MSG; message.obj=showedMsg; mHandler.sendMessage(message); } } socket.close(); bufferedReader.close(); printWriter.close(); } catch (IOException e) { e.printStackTrace(); } } } MyService import android.app.IntentService; import android.app.Service; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.os.IBinder; import android.support.annotation.Nullable; import android.util.Log; 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.ServerSocket; import java.net.Socket; import java.util.Random; public class MyService extends IntentService { public MyService() { super("MyService"); } private static final String TAG = "MyService"; private Boolean mIsServiceDestroy = false; private String[] mDefinedMessages = new String[]{ "你好啊,哈哈", "请问你叫什么名字啊?", "今天天气不错", "你知道吗,我可以同时和多个人聊天", "给你讲个笑话吧,你会发财" }; @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override protected void onHandleIntent(@Nullable Intent intent) { ServerSocket serverSocket = null; try { //监听本体8688端口 serverSocket = new ServerSocket(8688); } catch (IOException e) { e.printStackTrace(); Log.e(TAG, "failed"); } while (!mIsServiceDestroy) { try { //获取接收客户端信息 if (serverSocket != null) { final Socket socket = serverSocket.accept(); new Thread(new Runnable() { @Override public void run() { try { responseClient(socket); } catch (IOException e) { e.printStackTrace(); } } }).start(); } } catch (IOException e) { e.printStackTrace(); } } } private void responseClient(Socket socket) throws IOException{ //用于接收客户端消息 BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(socket.getInputStream())); //用于给客户端发送消息 PrintWriter printWriter=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()) ),true); printWriter.println("欢迎来到聊天室"); while (!mIsServiceDestroy){ String str=bufferedReader.readLine(); Log.d(TAG,"message from client"+str); if (str==null){ //客户端断开连接 break; } int i=new Random().nextInt(mDefinedMessages.length); String msg=mDefinedMessages[i]; printWriter.println(msg); } printWriter.close(); bufferedReader.close(); socket.close(); } @Override public void onDestroy() { Log.e(TAG,"destroy"); super.onDestroy(); } }

activitymain.xml

<RelativeLayout 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="com.example.yrc.socket.MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/text"/> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/editText" android:layout_alignParentBottom="true" android:layout_toLeftOf="@+id/button" android:layout_toStartOf="@+id/button" android:hint="say you want say" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentEnd="true" android:layout_alignParentRight="true" android:text="send" android:id="@+id/button" /> </RelativeLayout>
转载请注明原文地址: https://www.6miu.com/read-2250369.html

最新回复(0)