Related reading: Java Socket Chat Room Programming (II) Using socket to implement single chat room
There are already many examples of using sockets to implement chat on the Internet, but I have seen a lot of them, and there are more or less problems.
Here I will implement a relatively complete chat example and explain the logic in it.
Since the socket is relatively large, I will divide a few articles to write a relatively complete socket example.
Here we first implement the simplest function of server-client communication and client to realize the message push.
Purpose: The server establishes a connection with the client. The client can send messages to the server, and the server can push messages to the client.
1. Create a socket chat server using java
1. SocketUrls determines the IP address and port number
public class SocketUrls{// ip address public final static String IP = "192.168.1.110";// Port number public final static int PORT = 8888;}2. The entrance to the Main program
public class Main {public static void main(String[] args) throws Exception {new ChatServer().initServer();}}3. Bean entity class
UserInfoBean
public class Main {public static void main(String[] args) throws Exception {new ChatServer().initServer();}}Chat MessageBean
public class MessageBean extends UserInfoBean {private long messageId;// Message idprivate long groupId;// Group idprivate boolean isGoup;// Whether it is a group message private int chatType;// Message type;1, text;2, picture;3, short video;4, file;5, geographical location;6, voice;7, video call private String content;// Text message content private String errorMsg;// Error message private int errorCode;// Error code// Omit get/set method}4. ChatServer chat service, the most important program
public class ChatServer {// socket service private static ServerSocket server;public Gson gson = new Gson();/*** Initialize socket service*/public void initServer() {try {// Create a ServerSocket to listen to customer requests on port 8080 server = new ServerSocket(SocketUrls.PORT);createMessage();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}/*** Create message management and keep receiving messages*/private void createMessage() {try {System.out.println("waiting for user access: ");// Use accept() to block and wait for client requests Socket socket = server.accept();System.out.println("User access: " + socket.getPort());// Open a child thread to wait for another socket to join new Thread(new Runnable() {public void run() {createMessage();}}).start();// Send information to the client OutputStream output = socket.getOutputStream();// Get information from the client BufferedReader bff = new BufferedReader(new InputStreamReader(socket.getInputStream()));// Scanner scanner = new Scanner(socket.getInputStream());new Thread(new Runnable() {public void run() {try {String buffer;while (true) {// Enter BufferedReader from the console strin = new BufferedReader(new InputStreamReader(System.in));buffer = strin.readLine();// Because readLine uses a newline as the end point, add a newline buffer at the end += "/n";output.write(buffer.getBytes("utf-8"));// Send data output.flush();}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}).start();// Read the sent server information String line = null;// The loop keeps receiving messages from the current socket while (true) {Thread.sleep(500);// System.out.println("Content: " + bff.readLine());// Get the client's information while ((line = bff.readLine()) != null) {MessageBean messageBean = gson.fromJson(line, MessageBean.class);System.out.println("User: " + messageBean.getUserName());System.out.println("Content: " + messageBean.getContent());}}// server.close();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();System.out.println("Error: " + e.getMessage());}}}2. The Android side is used as a mobile side to connect to the server
1. Appliaction instantiates a global chat service
public class ChatAppliaction extends Application {public static ChatServer chatServer;public static UserInfoBean userInfoBean;@Overridepublic void onCreate() {super.onCreate();}}2. The IP address and port number are consistent with the server
3. The chat strength is the same as the server side
4. XML layout. Log in, chat
1. Log in
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><EditTextandroid:id="@+id/chat_name_text"android:layout_width="match_parent"android:layou t_height="wrap_content"android:hint="username"android:text="admin"/><EditTextandroid:id="@+id/chat_pwd_text"android:layout_width="match_parent"android:layout_height="wrap_content"android:hint="password"android:text="123123123a"android:inputType="numberPassword" /><Buttonandroid:id="@+id/chat_login_btn"android:layout_width="match_parent"android:layout_height="wrap_content"android:hint="Login" /></LinearLayout>
2. Chat
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation= "vertical"tools:context=".activity.MainActivity"><ScrollViewandroid:id="@+id/scrollView"android:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="0.9"><LinearLayoutandr oid:id="@+id/chat_ly"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"></LinearLayout></ScrollView><LinearLayoutandroid:layout_width="match_par ent"android:layout_height="wrap_content"android:orientation="horizontal"><EditTextandroid:id="@+id/chat_et"android:layout_width="0dp"android:layout_height="match_parent"android:layout_weight="0.8" /><Buttonandroid:id="@+id/send_btn"android:layout_width="0dp"android:layout_height="match_parent"android:layout_weight="0.2"android:text="send" /></LinearLayout></LinearLayout>
5. LoginActivity Login
public class LoginActivity extends AppCompatActivity {private EditText chat_name_text, chat_pwd_text;private Button chat_login_btn;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_login);chat_name_text = (EditText) findViewById(R.id.chat_name_text);chat_pwd_text = (EditText) findViewById(R.id.chat_pwd_text);chat_login_btn = (Button) findViewById(R.id.chat_login_btn);chat_login_btn.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {if (getLogin(chat_name_text.getText().toString().trim(), chat_pwd_text.getText().toString().trim())) {getChatServer();Intent intent = new Intent(LoginActivity.this, MainActivity.class);startActivity(intent);finish();}}});}private boolean getLogin(String name, String pwd) {if (TextUtils.isEmpty(name) || TextUtils.isEmpty(pwd)) return false;if (name.equals("admin") && pwd.equals("123123123a")) return true;return false;}private void getChatServer() {ChatAppliaction.chatServer = new ChatServer();}}6. MainActivity Chat
public class MainActivity extends AppCompatActivity {private LinearLayout chat_ly;private TextView left_text, right_view;private EditText chat_et;private Button send_btn;private ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);chat_ly = (LinearLayout) findViewById(R.id.chat_ly);chat_et = (EditText) findViewById(R.id.chat_et);send_btn = (Button) findViewById(R.id.send_btn);send_btn.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {ChatAppliaction.chatServer.sendMessage(chat_et.getText().toString().trim());chat_ly.addView(initRightView(chat_et.getText().toString().trim()));}});//Add message receiving queueChatAppliaction.chatServer.setChatHandler(new Handler() {@Overridepublic void handleMessage(Message msg) {if (msg.what == 1) {//After sending back the message, update uichat_ly.addView(initLeftView(msg.obj.toString()));}}});}/**Message to the right* @param messageContent* @return*/private View initRightView(String messageContent) {right_view = new TextView(this);right_view.setLayoutParams(layoutParams);right_view.setGravity(View.FOCUS_RIGHT);right_view.setText(messageContent);return right_view;}/**Message on the left* @param messageContent* @return*/private View initLeftView(String messageContent) {left_text = new TextView(this);left_text.setLayoutParams(layoutParams);left_text.setGravity(View.FOCUS_LEFT);left_text.setText(messageContent);return left_text;}}7. ChatServer chat logic, the most important
public class ChatServer {private Socket socket;private Handler handler;private MessageBean messageBean;private Gson gson = new Gson();// Get the output stream from the Socket object and construct the PrintWriter object PrintWriter printWriter;InputStream input;OutputStream output;DataOutputStream dataOutputStream;public ChatServer() {initMessage();initChatServer();}/*** Message queue, used to pass messages** @param handler*/public void setChatHandler(Handler handler) {this.handler = handler;}private void initChatServer() {//Open thread to receive message receiveMessage();}/*** Initialize user information*/private void initMessage() {messageBean = new MessageBean();messageBean.setUserId(1);messageBean.setMessageId(1);messageBean.setChatType(1);messageBean.setUserName("admin");ChatAppliaction.userInfoBean = messageBean;}/*** Send a message** @param contentMsg*/public void sendMessage(String contentMsg) {try {if (socket == null) {Message message = handler.obtainMessage();message.what = 1;message.obj = "The server has been closed";handler.sendMessage(message);return;}byte[] str = contentMsg.getBytes("utf-8");//Turn the content utf-8String aaa = new String(str);messageBean.setContent(aaa);String messageJson = gson.toJson(messageBean);/*** Because the readLine() on the server is blocking reading* If it cannot read the newline character or the output stream ends, it will be blocked there* So a newline character is added at the end of the json message to tell the server that the message has been sent* */messageJson += "/n";output.write(messageJson.getBytes("utf-8"));// newline print output.flush(); // refresh the output stream so that the Server receives the string immediately} catch (Exception e) {e.printStackTrace();Log.e("test", "Error:" + e.toString());}}/*** Receive the message, in the child thread */private void receiveMessage() {new Thread(new Runnable() {@Overridepublic void run() {try {// Send a client request to the native port 8080 socket = new Socket(SocketUrls.IP, SocketUrls.PORT);// Get the input stream from the Socket object and construct the corresponding BufferedReader object printWriter = new PrintWriter(socket.getOutputStream());input = socket.getInputStream();output = socket.getOutputStream();dataOutputStream = new DataOutputStream(socket.getOutputStream());// Get information from the client BufferedReader bff = new BufferedReader(new InputStreamReader(input));// Read the sent server information String line; while (true) {Thread.sleep(500);// Get the information from the client while ((line = bff.readLine()) != null) {Log.i("socket", "Content: " + line);Message message = handler.obtainMessage();message.obj = line;message.what = 1;handler.sendMessage(message);}if (socket == null)break;}output.close();//Close Socket output stream input.close();//Close Socket input stream socket.close();//Close Socket} catch (Exception e) {e.printStackTrace();Log.e("test", "Error:" + e.toString());}}}).start();}}}By the way, all the code has been completed.
This demo can enable the mobile phone to send messages to the server and the server to the mobile phone.
This demo can be regarded as a push function, but the real push is not that simple. As a beginner of sockets, you can see the ideas of socket programming.
The above is the Java Socket chat room programming introduced by the editor (1) to use socket to implement chat message push. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!