最近APP开发,需要一个聊天功能
思路是 使用openfire
整理了一下思路: 先从最原始的开始
原始socket-->nio>mina>openfire
今天实现,一个 服务端,多个客户端连接和会话,比较简单,了解即可
一: 服务端
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server1 {
private int port=1113;
private ServerSocket server;
private static int count=0;
public static void main(String[] args) {
Server1 test=new Server1();
test.begin();
}
public void begin()
{
try {
server = new ServerSocket(port);
while(true)
{
Socket socket = server.accept();
MyThread sunthread= new MyThread(socket,count);
sunthread.start();
count++;
}
}
catch (Exception e) {
// TODO: handle exception
}
}
class MyThread extends Thread
{
private Socket mysocket;
private int portname;
public MyThread(Socket socket,int count) {
this.mysocket=socket;
portname=socket.getPort();
System.out.println("第:"+count+"个客户端接入"+portname);
}
@Override
public void run() {
while(true)
{
BufferedReader in;
PrintWriter outputWriter = null;
try {
in = new BufferedReader(new InputStreamReader( mysocket.getInputStream()));
String line=in.readLine();
System.out.println("服务器收到"+portname+"的消息:"+line);
outputWriter=new PrintWriter(mysocket.getOutputStream());
outputWriter.println("你好:"+portname+"收到您的信息:"+line);
outputWriter.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
2 客户端
package socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class TestMain {
private static final String HOSTNAME = "127.0.0.1";
private static final int PORT = 1113;
public static void main(String[] args) {
String inputstring;
BufferedReader readin;
PrintWriter outputWriter = null;
try {
Socket clientSocket=new Socket(HOSTNAME, PORT);
System.out.println("本地port:"+clientSocket.getLocalPort());
readin=new BufferedReader(new InputStreamReader(System.in));
outputWriter=new PrintWriter(clientSocket.getOutputStream());
//读
BufferedReader inputReader=new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
inputstring=readin.readLine();
while (!readin.equals("bye"))
{
// System.out.println("输入的是"+inputstring);
//往外写
outputWriter.println(inputstring);
outputWriter.flush();
System.out.println("----》》"+inputReader.readLine());
inputstring=readin.readLine();
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
outputWriter.close();
}
}
}
效果:
服务端 启动, 客户端多run as javaapplication几次 即可生成几个客户端
服务端:
客户端: