English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Socket Chat Room Programming (Part I) Using Socket to Implement Chat Message Push

Related reading:Java Socket Chat Room Programming (Part II) Using Socket to Implement Single Chat Chat Room

There are already many examples of chat using socket on the Internet, but I have seen many of them, and there are some problems in many of them.

Here I will implement a more complete chat example and explain the logic within it.

Since socket is a large part, I will divide it into several parts to write a more complete socket example.

Here we will first implement the simplest server-client communication, to achieve the message push function.

Purpose: Establish a connection between the server and the client, the client can send messages to the server, and the server can push messages to the client.

1,Use Java to establish a socket chat server

1,Determine IP address and port number of SocketUrls

public class SocketUrls{
// IP address
public final static String IP = "192.168.1.110";
// Port number
public final static int PORT = 8888;
}

2,Main program entry

public class Main {
public static void main(String[] args) throws Exception {
new ChatServer().initServer();
}
}

3,Bean entity class

User information UserInfoBean

public class Main {
public static void main(String[] args) throws Exception {
new ChatServer().initServer();
}
}

Chat information MessageBean

public class MessageBean extends UserInfoBean {
private long messageId;// Message ID
private long groupId;// Group ID
private boolean isGroup;// Is it a group message
private int chatType;// Message type;1,text;2,image;3,short video;4,file;5,geolocation;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 main 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 on port8080 to listen for customer requests
server = new ServerSocket(SocketUrls.PORT);
createMessage();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Create a message management, always receiving messages
*/
private void createMessage() {
try {
System.out.println("Waiting for user connection: ");
// Use accept() to block and wait for customer requests
Socket socket = server.accept();
System.out.println("User connected: ", + socket.getPort());
// Start a sub-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();
// Obtain 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) {
// Input from the console
BufferedReader string = new BufferedReader(new InputStreamReader(System.in));
buffer = string.readLine();
// Because readLine ends with a newline character, a newline is added at the end
buffer += "\n";
output.write(buffer.getBytes("utf"}}-8"));
// Send data
output.flush();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
// Read information sent from the server
String line = null;
// Loop to continuously receive messages sent from the current socket
while (true) {
Thread.sleep(500);
// System.out.println("Content : ", + bff.readLine());
// Obtain client 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 block
e.printStackTrace();
System.out.println("Error : ", + e.getMessage());
}
}
}

2,Android side as the mobile end to connect to the server

1,application instantiate a global chat service

public class ChatApplication extends Application {
public static ChatServer chatServer;
public static UserInfoBean userInfoBean;
@Override
public void onCreate() {
super.onCreate();
}
}

2,IP address and port number should be consistent with the server

3,chat functionality is similar to the server side

4,xml layout. Login, chat

1,login

<?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">
<EditText
android:id="@"+id/chat_name_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="username"
android:text="admin"/>
<EditText
android:id="@"+id/chat_pwd_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="password"
android:text="123123123a"
android:inputType="numberPassword" />
<Button
android: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">
<ScrollView
android:id="@"+id/scrollView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.9">
<LinearLayout
android:id="@"+id/chat_ly"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
</ScrollView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="@"+id/chat_et"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.8" />
<Button
android:id="@"+id/send_btn"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.2"
android:text="send" />
</LinearLayout>
</LinearLayout>

5LoginActivity login

public class LoginActivity extends AppCompatActivity {
private EditText chat_name_text, chat_pwd_text;
private Button chat_login_btn;
@Override
protected 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() {
@Override
public 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();
}
}

6Chat activity for MainActivity

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);
@Override
protected 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() {
@Override
public void onClick(View v) {
ChatAppliaction.chatServer.sendMessage(chat_et.getText().toString().trim());
chat_ly.addView(initRightView(chat_et.getText().toString().trim()));
}
});
//Add message receiving queue
ChatAppliaction.chatServer.setChatHandler(new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 1) {
//Update UI after receiving the message back
chat_ly.addView(initLeftView(msg.obj.toString()));
}
}
});
}
/**Right-aligned message
* @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;
}
/**Left-aligned message
* @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;
}
}

7The chat logic, the most important part of

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 a 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() {
//Start a thread to receive messages
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 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");//Convert content to utf-8
String aaa = new String(str);
messageBean.setContent(aaa);
String messageJson = gson.toJson(messageBean);
/**
* Because the readLine() on the server side is a blocking read
* If it cannot read the newline character or the output stream ends, it will be blocked there
* Therefore, add a newline character at the end of the json message to inform the server that the message has been sent
* */
messageJson += "\n";
output.write(messageJson.getBytes("utf-8"));// New line print
output.flush(); // Refresh the output stream to make the Server receive the string immediately
} catch (Exception e) {
e.printStackTrace();
Log.e("test", "Error:") + e.toString());
}
}
/**
* Receive message, in a sub-thread
*/
private void receiveMessage() {
new Thread(new Runnable() {
@Override
public void run() {
try {
// Send to the local808Send customer request from port 0
socket = new Socket(SocketUrls.IP, SocketUrls.PORT);
// Obtain 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());
// Obtain information from the client
BufferedReader bff = new BufferedReader(new InputStreamReader(input));
// Read information sent from the server
String line;
while (true) {
Thread.sleep(500);
// Obtain client information
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();
}
}

Writing here, all the code has been completed.

This demo can realize sending messages from the mobile terminal to the server, and sending messages from the server to the mobile terminal.

This demo can be considered as a push function, but the real push is not so simple. As an introduction to the socket, you can see the thought of socket programming from it.

The above is the Java Socket Chat Room Programming (Part 1) introduced by the editor to implement chat message push using socket, hoping it will be helpful to everyone. If you have any questions, please leave a message, and the editor will reply to everyone in time. We are also very grateful for everyone's support for the Yelling Tutorial website!

Declaration: The content of this article is from the Internet, the copyright belongs to the original author, the content is contributed and uploaded by Internet users spontaneously, this website does not own the copyright, does not undergo artificial editing, and does not bear relevant legal liabilities. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email for reporting. Provide relevant evidence, and once verified, this site will immediately delete the suspected infringing content.)

You May Also Like