用JAVA编写一个客户机服务器聊天程序
服务器端(注意要先启动服务器端)
import javaio;
import javanet;
import javaawt;
import javaawtevent;
public class server extends Frame implements ActionListener {
Label label = new Label("交谈内容");
Panel panel = new Panel();
TextField tf = new TextField(10);
TextArea ta = new TextArea();
ServerSocket server;
Socket client;
InputStream in;
OutputStream out;
public server() {
super("服务器");
setSize(250, 250);
paneladd(label);
paneladd(tf);
tfaddActionListener(this);
add("North", panel);
add("Center", ta);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
Systemexit(0);
}
});
show();
try {
server = new ServerSocket(4000);
client = serveraccept();
taappend("客户机是:" + clientgetInetAddress()getHostName() + "\n\n");
in =clientgetInputStream();
out= clientgetOutputStream();
} catch (IOException ioe) {
}
while (true) {
try {
byte[] buf = new byte[256];
inread(buf);
String str = new String(buf);
taappend("客户机说:" + str + "\n\n");
} catch (IOException e) {
}
}
}
public void actionPerformed(ActionEvent e) {
try {
String str = tfgetText();
byte[] buf = strgetBytes();
tfsetText(null);
outwrite(buf);
taappend("我说:" + str + "\n");
} catch (IOException ioe) {
}
}
public static void main(String[] args) {
new server();
}
}
import javaio;
import javanet;
import javaawt;
import javaawtevent;
public class client extends Frame implements ActionListener {
Label label = new Label("交谈内容");
Panel panel = new Panel();
TextField tf = new TextField(10);
TextArea ta = new TextArea();
Socket client;
InputStream in;
OutputStream out;
public client() {
super("客户机");
setSize(250, 250);
paneladd(label);
paneladd(tf);
tfaddActionListener(this);
add("North", panel);
add("Center", ta);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
Systemexit(0);
}
});
show();
try {
client = new Socket(InetAddressgetLocalHost(), 4000);
taappend("服务器是:" + clientgetInetAddress()getHostName() + "\n\n");
in = clientgetInputStream();
out = clientgetOutputStream();
} catch (IOException ioe) {
}
while (true) {
try {
byte[] buf = new byte[256];
inread(buf);
String str = new String(buf);
taappend("服务器说:" + str + "\n");
} catch (IOException e) {
}
}
}
public void actionPerformed(ActionEvent e) {
try {
String str = tfgetText();
byte[] buf = strgetBytes();
tfsetText(null);
outwrite(buf);
taappend("我说:" + str + "\n");
} catch (IOException iOE) {
}
}
public static void main(String args[]) {
new client();
}
}
这个只能在自己一台电脑上先启动服务器再启动客户端才行,要想一台机子启动服务器端一台机子启动客户端需要把客户端的 client = new Socket(InetAddressgetLocalHost(), 4000);改成 client = new Socket("服务器Ip", 4000);(前提是两台机子连在局域网里面的)
两者都可以不过java的垃圾回收机制因为是自动的所以执行客户端程序的时候效率特别慢一般用于服务器端或WEB开发学java的重点就是以j2ee技术为核心的。想写客户端之类的用C语言是最佳的不过内存处理机制全部自己编写难度不是一般的高。
主从Reactor多线程Nio结构,主从Reactor线程模型的特点是:服务端用于接收客户端连接的不再是个1个单独的NIO线程,而是一个独立的NIO线程池。Acceptor接收到客户端TCP连接请求处理完成后(可能包含接入认证等),将新创建的SocketChannel注册到IO线程池(sub reactor线程池)的某个IO线程上,由它负责SocketChannel的读写和编解码工作。Acceptor线程池仅仅只用于客户端的登陆、握手和安全认证,一旦链路建立成功,就将链路注册到后端subReactor线程池的IO线程上,由IO线程负责后续的IO操作。
利用主从NIO线程模型,可以解决1个服务端监听线程无法有效处理所有客户端连接的性能不足问题。
它的工作流程总结如下:
从主线程池中随机选择一个Reactor线程作为Acceptor线程,用于绑定监听端口,接收客户端连接;
Acceptor线程接收客户端连接请求之后创建新的SocketChannel,将其注册到主线程池的其它Reactor线程上,由其负责接入认证、IP黑白名单过滤、握手等操作;
步骤2完成之后,业务层的链路正式建立,将SocketChannel从主线程池的Reactor线程的多路复用器上摘除,重新注册到Sub线程池的线程上,用于处理I/O的读写操作。
服务器监听端口 做个无限循环 接到一个连接就创建一个通道线程,并将通道线程存储到一个list集合中
import javaioBufferedReader;import javaioIOException;
import javaioInputStreamReader;
import javaioPrintWriter;
import javanetServerSocket;
import javanetSocket;
import javatextSimpleDateFormat;
import javautilArrayList;
import javautilDate;
import javautilList;
/
4用socket通讯写出多个客户端和一个服务器端的通讯,
要求客户发送数据后能够回显相同的数据(回显功能)(实用TCP方式)。
/
public class Test4Server {
// 主入口
public static void main(String[] args) throws IOException {
scoketServer();
}
// 开启的tcp8888监听端口
public static void scoketServer() throws IOException {
ServerSocket server = new ServerSocket(8888);
while (true) {
// 未连通前线程阻塞,连通后开启一个socket通道线程后继续监听8888端口
Socket socket = serveraccept();
Systemoutprintln(socketgetInetAddress()getHostAddress()
+ "连接进入");
new SocketThread(socket)start();
}
}
}
// 一个服务器端口中监听多个客服端通道线程
class SocketThread extends Thread {
// 所有通道写入流的集合
private static List<PrintWriter> list =new ArrayList<PrintWriter>();
private BufferedReader bufferedReader;
private PrintWriter printWriter;
public SocketThread(Socket socket) throws IOException {
thisbufferedReader = new BufferedReader(new InputStreamReader(socket
getInputStream()));
thisprintWriter = new PrintWriter(socketgetOutputStream());
listadd(printWriter);
}
@Override
public void run() {
String string = null;
while (true) {
try {
// 服务器在通道中读到的信息回显给客服端
string = bufferedReaderreadLine();
Systemoutprintln("客服端信息:" + string);
for(PrintWriter printWriter:list ){
printWriterwrite("服务器回显:" + string + "\r\n");
printWriterflush();
}
} catch (IOException e) {
}
}
}
}
客服端代码 可以用在局域网中用多台来连接测试
import javaioBufferedReader;import javaioIOException;
import javaioInputStreamReader;
import javaioPrintWriter;
import javanetSocket;
import javautilScanner;
public class Test4Client {
public static Object obj = new Object();
// 客服端的主入口
public static void main(String[] args) throws IOException {
socketClient();
}
// 与服务器连通地址本机(127001),局域网中其他机器是(服务器在局域网中的ip地址) 端口都是8888
public static void socketClient() throws IOException {
Socket socket = new Socket("127001", 8888);
if (socketisConnected()) {
// 如果连接成功了就开启写和读的进程
new writer(socket)start();
new read(socket)start();
} else {
Systemoutprintln("服务器未开启");
}
}
}
// 写入到通道的线程
class writer extends Thread {
@SuppressWarnings("unused")
private Socket socket;
private PrintWriter printWriter;
private Scanner scanner = new Scanner(Systemin);
private String str = null;
public writer(Socket socket) throws IOException {
thissocket = socket;
thisprintWriter = new PrintWriter(socketgetOutputStream());
}
@Override
public void run() {
scanneruseDelimiter("\r\n");
while (true) {
Systemoutprint("请输入信息:");
// 产生扫描器的线程阻塞
str = scannernext();
Systemoutprintln("我说:"+str);
printWriterwrite(str + "\r\n");
printWriterflush();
try {
Threadsleep(200);
} catch (InterruptedException e) {
eprintStackTrace();
}
}
}
}
// 从通道中读取的线程
class read extends Thread {
private Socket socket;
private BufferedReader bufferedReader;
private String str = null;
public read(Socket socket) throws IOException {
thissocket = socket;
thisbufferedReader = new BufferedReader(new InputStreamReader(socket
getInputStream()));
}
@Override
public void run() {
while (true) {
try {
str = bufferedReaderreadLine();
Systemoutprintln(str);
} catch (IOException e) {
}
try {
Threadsleep(200);
} catch (InterruptedException e) {
eprintStackTrace();
}
}
}
}
0条评论