用JAVA编写一个客户机服务器聊天程序

用JAVA编写一个客户机服务器聊天程序,第1张

服务器端(注意要先启动服务器端)

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);(前提是两台机子连在局域网里面的)

服务端码在服务器上执行,客户端代码在客户端执行。你不能用客户端代码去控制服务器,只能通过客户端代码将数据发送到服务器,由服务器代码执行。一个客户端控件加上上runat=“server”以后就变成了服务端控件,就可以在aspxcs里控制这个控件了。

程序分Server和Client

服务器端打开侦听的端口,一有客户端连接就创建两个新的线程来负责这个连接

一个负责客户端发送的信息(ClientMsgCollectThread 类),

另一个负责通过该Socket发送数据(ServerMsgSendThread )

Serverjava代码如下:

/

创建日期 2009-3-7

TODO 要更改此生成的文件的模板,请转至

窗口 - 首选项 - Java - 代码样式 - 代码模板

/

package faueMutiUser;

import javaioBufferedReader;

import javaioIOException;

import javaioInputStreamReader;

import javaioPrintWriter;

import javanetServerSocket;

import javanetSocket;

/

服务器端

@author Faue

/

public class Server extends ServerSocket {

private static final int SERVER_PORT = 10000;

/

构造方法,用于实现连接的监听

@throws IOException

/

public Server() throws IOException {

super(SERVER_PORT);

try {

while (true) {

Socket socket = superaccept();

new Thread(new ClientMsgCollectThread(socket), "getAndShow"

+ socketgetPort())start();

new Thread(new ServerMsgSendThread(socket), "send"

+ socketgetPort())start();

}

} catch (IOException e) {

eprintStackTrace();

}

}

public static void main(String[] args) throws IOException {

new Server();

}

/

该类用于创建接收客户端发来的信息并显示的线程

@author Faue

@version 100

/

class ClientMsgCollectThread implements Runnable {

private Socket client;

private BufferedReader in;

private StringBuffer inputStringBuffer = new StringBuffer("Hello");

/

得到Socket的输入流

@param s

@throws IOException

/

public ClientMsgCollectThread(Socket s) throws IOException {

client = s;

in = new BufferedReader(new InputStreamReader(client

getInputStream(), "GBK"));

}

public void run() {

try {

while (!clientisClosed()) {

inputStringBufferdelete(0, inputStringBufferlength());

inputStringBufferappend(inreadLine());

Systemoutprintln(getMsg(inputStringBuffertoString()));

}

} catch (IOException e) {

//eprintStackTrace();

Systemoutprintln(clienttoString() + " is closed!");

}

}

/

构造显示的字符串

@param line

@return

/

private String getMsg(String line) {

return clienttoString() + " says:" + line;

}

}

/

该类用于创建发送数据的线程

@author Faue

@version 100

/

class ServerMsgSendThread implements Runnable {

private Socket client;

private PrintWriter out;

private BufferedReader keyboardInput;

private StringBuffer outputStringBuffer = new StringBuffer("Hello");

/

得到键盘的输入流

@param s

@throws IOException

/

public ServerMsgSendThread(Socket s) throws IOException {

client = s;

out = new PrintWriter(clientgetOutputStream(), true);

keyboardInput = new BufferedReader(new InputStreamReader(Systemin));

}

public void run() {

try {

while (!clientisClosed()) {

outputStringBufferdelete(0, outputStringBufferlength());

outputStringBufferappend(keyboardInputreadLine());

outprintln(outputStringBuffertoString());

}

} catch (IOException e) {

//eprintStackTrace();

Systemoutprintln(clienttoString() + " is closed!");

}

}

}

}

客户端:

实现基于IP地址的连接,连接后也创建两个线程来实现信息的发送和接收

/

创建日期 2009-3-7

/

package faueMutiUser;

import javaioBufferedReader;

import javaioIOException;

import javaioInputStreamReader;

import javaioPrintWriter;

import javanetSocket;

/

客户端

@author Faue

/

public class Client {

private Socket mySocket;

/

创建线程的构造方法

@param IP

@throws IOException

/

public Client(String IP) throws IOException {

try {

mySocket = new Socket(IP, 10000);

new Thread(new ServerMsgCollectThread(mySocket), "getAndShow"

+ mySocketgetPort())start();

new Thread(new ClientMsgSendThread(mySocket), "send"

+ mySocketgetPort())start();

} catch (IOException e) {

//eprintStackTrace();

Systemoutprintln("ServerIP:" + IP

+ " port:10000 can not be Connected");

}

}

public static void main(String[] args) throws IOException {

try {

new Client(args[0]);

} catch (Exception e) {

Systemoutprintln("输入的IP地址错误");

}

}

/

该类用于创建接收服务端发来的信息并显示的线程

@author Faue

@version 100

/

class ServerMsgCollectThread implements Runnable {

private Socket client;

private BufferedReader in;

private StringBuffer inputStringBuffer = new StringBuffer("Hello");

/

得到Socket的输入流

@param s

@throws IOException

/

public ServerMsgCollectThread(Socket s) throws IOException {

client = s;

in = new BufferedReader(new InputStreamReader(client

getInputStream(), "GBK"));

}

public void run() {

try {

while (!clientisClosed()) {

inputStringBufferdelete(0, inputStringBufferlength());

inputStringBufferappend(inreadLine());

Systemoutprintln(getMsg(inputStringBuffertoString()));

}

} catch (IOException e) {

//eprintStackTrace();

Systemoutprintln(clienttoString() + " is closed!");

Systemexit(0);

}

}

/

构造输入字符串

@param line

@return

/

private String getMsg(String line) {

return clienttoString() + " says:" + line;

}

}

/

该类用于创建发送数据的线程

@author Faue

@version 100

/

class ClientMsgSendThread implements Runnable {

private Socket client;

private PrintWriter out;

private BufferedReader keyboardInput;

private StringBuffer outputStringBuffer = new StringBuffer("Hello");

/

得到键盘的输入流

@param s

@throws IOException

/

public ClientMsgSendThread(Socket s) throws IOException {

client = s;

out = new PrintWriter(clientgetOutputStream(), true);

keyboardInput = new BufferedReader(new InputStreamReader(Systemin));

}

public void run() {

try {

while (!clientisClosed()) {

outputStringBufferdelete(0, outputStringBufferlength());

outputStringBufferappend(keyboardInputreadLine());

outprintln(outputStringBuffertoString());

}

outprintln("--- See you, bye! ---");

} catch (IOException e) {

//eprintStackTrace();

Systemoutprintln(clienttoString() + " is closed!");

Systemexit(0);

}

}

}

}

如果对您有帮助,请记得采纳为满意答案,谢谢!祝您生活愉快!

vaela

DABAN RP主题是一个优秀的主题,极致后台体验,无插件,集成会员系统
网站模板库 » 用JAVA编写一个客户机服务器聊天程序

0条评论

发表评论

提供最优质的资源集合

立即查看 了解详情