socket通信-服务端-客户端-实现多个客户端群聊

时间:2022-12-21 22:14:54

socket通信-服务端-客户端-实现多个客户端群聊做出来大致就是这个界面。

服务器:

package hjc.testServer;
public class MyServerSocket {
public static void main(String[] args) {
new ServerListener().start();
}
}
----------------------------------------------------------
package hjc.testServer;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.JOptionPane;
public class ServerListener extends Thread {
public void run(){
try {
ServerSocket serverSocket = new ServerSocket(12345);
while(true){
Socket socket=serverSocket.accept();
JOptionPane.showMessageDialog(null, "有客户端链接到了");
System.out.println("链接到了");
ChartSocket cs=new ChartSocket(socket);
cs.start();
ChatManager.getChatManager().add(cs);
}
} catch (IOException e) {
e.printStackTrace();
}
}

}
----------------------------------------------------------
package hjc.testServer;
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 ChartSocket extends Thread {
Socket socket;
BufferedWriter bw;
BufferedReader br;
public ChartSocket(Socket s) {
this.socket = s;
try {
bw = new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream(), "utf-8"));
br = new BufferedReader(new InputStreamReader(
socket.getInputStream(), "utf-8"));
} catch (IOException e) {
e.printStackTrace();
}
}

public void out(String out) {
try {
bw.write(out + "\n");// 必须要加换行符号,不然数据发不出去
bw.flush();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

public void run(){
try {
// BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"));
String line=null;
while((line=br.readLine())!=null){//reaadline是个阻塞函数 没有读取到会一直处于阻塞状态
System.out.println("读取到了信息");
System.out.println("客户端发来数据:"+line);
ChatManager.getChatManager().publish(this, line);
System.out.println("写入了信息");
}
br.close();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
----------------------------------------------------------
package hjc.testServer;

import java.util.Vector;

public class ChatManager {

/**
* @param args
*/

private ChatManager(){ }
private static final ChatManager cm=new ChatManager();
public static ChatManager getChatManager(){
return cm;
}
Vector<ChartSocket> vector =new Vector<ChartSocket>();
public void add(ChartSocket cs){
vector.add(cs);
}
public void publish(ChartSocket cs,String out){
for(int i=0;i<vector.size();i++){//遍历所有de chartsocket
ChartSocket csChartSocket=vector.get(i);//获取循环中的第I个对象 telnet localhost 12345
if(!cs.equals(csChartSocket)){//bushi 本身
csChartSocket.out(out);
System.out.println("将信息发送给所有客户 调用pulish: "+out);

}
}
}
}
==========================================================
客户端:

package com.example.androidclient;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;


import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

EditText ip;
EditText editText;
TextView text;
Button send, connect;

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

ip = (EditText) findViewById(R.id.ip);
editText = (EditText) findViewById(R.id.edit);
text = (TextView) findViewById(R.id.text);
send = (Button) findViewById(R.id.send);
connect = (Button) findViewById(R.id.connect);

connect.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
connect();

}
});

send.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
send();

}
});

}

// ----------------------------------------------
Socket socket = null;
BufferedReader reader = null;
BufferedWriter writer = null;
public void connect() {
AsyncTask<Void, String, Void> read = new AsyncTask<Void, String, Void>() {
protected Void doInBackground(Void... params) {
try {
socket = new Socket("192.168.191.1", 12345);
writer = new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream(),"utf-8"));
Log.e("test", "writerwriterwriterwriter");

reader = new BufferedReader(
new InputStreamReader(
socket.getInputStream(),"utf-8"));
Log.e("test", "dream......................");
publishProgress("@Sucess");
} catch (UnknownHostException e1) {
Toast.makeText(MainActivity.this, "无法建立链接",
Toast.LENGTH_SHORT).show();
e1.printStackTrace();
} catch (IOException e1) {
Toast.makeText(MainActivity.this, "无法建立链接",
Toast.LENGTH_SHORT).show();
e1.printStackTrace();
}
try {
String line;
while ((line = reader.readLine()) != null) {
publishProgress(line);
Log.e("test", " readling()");
}
} catch (IOException e) {
e.printStackTrace();
}

return null;
}
@Override
protected void onProgressUpdate(String... values) {
if (values[0].equals("@Sucess")) {
Toast.makeText(MainActivity.this, "建立链接",
Toast.LENGTH_SHORT).show();

}else {
Toast.makeText(MainActivity.this, "收到数据!",
Toast.LENGTH_SHORT).show();
Log.e("test", "others");
text.append("别人:" + values[0]+"\n");
Log.e("test", "others");
}
}

};
read.execute();

}

public void send() {
try {
writer.write(editText.getText().toString() + "\n");
writer.flush();
text.append("我说 : " + editText.getText().toString() + "\n");
editText.setText("");
} catch (IOException e) {
e.printStackTrace();
}

}

}

登录那个跳转页和XML的编写比较简单,读者可自己写一个简单的页面。