自学了一个月J2SE后,写了个局域网聊天的小程序,请高手指教,
小弟我自知水平不济,暑假我打算去北京培训J2EE,请教高手经验
//-------------------------ChatClient.java--------------------------public class ChatClient { /**
* @param args
*/
public static void main(String[] args) { Manager m = new Manager();
m.working();
}}//---------------------Manager.java--------------------//协调管理类
public class Manager {
public MainFrame mf = null;
public Thread ser = null;
Manager(){
mf = new MainFrame("FrameXXXX");
}
public void working(){
mf.lanuchFrame();
//启动Server>>>>>>
ser = new Thread(new ServerThread(mf));
ser.start();
}}//----------------MainFrame.java-----------------//主框架代码
import java.awt.*;
import java.awt.event.*;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
public class MainFrame extends Frame {
/**
*
*/
private static final long serialVersionUID = 1L;
public TextField textInput = null;
public TextArea textShow = null;
public Button btn = null;
public TextField textAdress = null;
public String strAdress = null;
public Socket s = null;
public DataInputStream dis = null;
public DataOutputStream dos = null;
public static boolean bConnect = false;
MainFrame(String name){
super(name);
}
public void lanuchFrame(){
Rectangle r = new Rectangle(100, 100, 300, 300);
this.setBounds(r);
textInput = new TextField();
textShow = new TextArea();
this.add(textInput, BorderLayout.SOUTH);
this.add(textShow, BorderLayout.NORTH);
btn = new Button("连接");
textAdress = new TextField();
Panel p = new Panel(new GridLayout(1, 2));
p.add(textAdress);
p.add(btn);
this.add(p, BorderLayout.CENTER);
this.pack();
this.setVisible(true);
this.addWindowListener(new MonitorWindowClose());
textInput.addKeyListener(new MonitorKeyEnter());
btn.addActionListener(new MonitorConn(this));
} class MonitorWindowClose extends WindowAdapter{ @Override
public void windowClosing(WindowEvent arg0) {
disConnect();
System.exit(0);
}
}
class MonitorKeyEnter extends KeyAdapter{ @Override
public void keyReleased(KeyEvent arg0) {
if(arg0.getKeyCode() == KeyEvent.VK_ENTER){
if(MainFrame.bConnect){
textShow.append(s.getLocalAddress() + ": " + getInputText() + "\n");
sendData(getInputText());
textInput.setText("");
}else{
textShow.append("server connect fail!\n");
}
}
}
} public String getInputText() {
return textInput.getText();
}
public boolean connect(String adress){
//System.out.println("Mainframe: " + adress);
try{
s = new Socket(adress, 9999);
dos = new DataOutputStream(s.getOutputStream());
return true;
}catch(UnknownHostException uhe){
this.textShow.append("找不到 相应server\n");
this.disConnect();
return false;
//uhe.printStackTrace();
}catch(IOException ioe){
//ioe.printStackTrace();
this.textShow.append("io error!\n");
return false;
}
}
public void disConnect(){
try{
if(dos != null){
dos.close();
}
if(s != null){
s.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
public void sendData(String str){
try{
dos.writeUTF(str);
dos.flush();
}catch(SocketException e){
this.textShow.append("对方退出>>>>\n");
this.textShow.append(str + "发送失败!\n");
}catch(IOException ioe2){
ioe2.printStackTrace();
}
}
}
小弟我自知水平不济,暑假我打算去北京培训J2EE,请教高手经验
//-------------------------ChatClient.java--------------------------public class ChatClient { /**
* @param args
*/
public static void main(String[] args) { Manager m = new Manager();
m.working();
}}//---------------------Manager.java--------------------//协调管理类
public class Manager {
public MainFrame mf = null;
public Thread ser = null;
Manager(){
mf = new MainFrame("FrameXXXX");
}
public void working(){
mf.lanuchFrame();
//启动Server>>>>>>
ser = new Thread(new ServerThread(mf));
ser.start();
}}//----------------MainFrame.java-----------------//主框架代码
import java.awt.*;
import java.awt.event.*;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
public class MainFrame extends Frame {
/**
*
*/
private static final long serialVersionUID = 1L;
public TextField textInput = null;
public TextArea textShow = null;
public Button btn = null;
public TextField textAdress = null;
public String strAdress = null;
public Socket s = null;
public DataInputStream dis = null;
public DataOutputStream dos = null;
public static boolean bConnect = false;
MainFrame(String name){
super(name);
}
public void lanuchFrame(){
Rectangle r = new Rectangle(100, 100, 300, 300);
this.setBounds(r);
textInput = new TextField();
textShow = new TextArea();
this.add(textInput, BorderLayout.SOUTH);
this.add(textShow, BorderLayout.NORTH);
btn = new Button("连接");
textAdress = new TextField();
Panel p = new Panel(new GridLayout(1, 2));
p.add(textAdress);
p.add(btn);
this.add(p, BorderLayout.CENTER);
this.pack();
this.setVisible(true);
this.addWindowListener(new MonitorWindowClose());
textInput.addKeyListener(new MonitorKeyEnter());
btn.addActionListener(new MonitorConn(this));
} class MonitorWindowClose extends WindowAdapter{ @Override
public void windowClosing(WindowEvent arg0) {
disConnect();
System.exit(0);
}
}
class MonitorKeyEnter extends KeyAdapter{ @Override
public void keyReleased(KeyEvent arg0) {
if(arg0.getKeyCode() == KeyEvent.VK_ENTER){
if(MainFrame.bConnect){
textShow.append(s.getLocalAddress() + ": " + getInputText() + "\n");
sendData(getInputText());
textInput.setText("");
}else{
textShow.append("server connect fail!\n");
}
}
}
} public String getInputText() {
return textInput.getText();
}
public boolean connect(String adress){
//System.out.println("Mainframe: " + adress);
try{
s = new Socket(adress, 9999);
dos = new DataOutputStream(s.getOutputStream());
return true;
}catch(UnknownHostException uhe){
this.textShow.append("找不到 相应server\n");
this.disConnect();
return false;
//uhe.printStackTrace();
}catch(IOException ioe){
//ioe.printStackTrace();
this.textShow.append("io error!\n");
return false;
}
}
public void disConnect(){
try{
if(dos != null){
dos.close();
}
if(s != null){
s.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
public void sendData(String str){
try{
dos.writeUTF(str);
dos.flush();
}catch(SocketException e){
this.textShow.append("对方退出>>>>\n");
this.textShow.append(str + "发送失败!\n");
}catch(IOException ioe2){
ioe2.printStackTrace();
}
}
}
解决方案 »
- 一个用jdbc连接sql server 2005发生异常的问题
- java中的方向键
- 一个数据库连接问题!
- 一个正则表达式的问题
- 能不能指教以下八java农成exe的软件阿
- 菜菜的问下,JDK6是不是不支持范型啊?
- 用jar打包的问题
- 我用sun.misc.BASE64Encoder进行编码,但在JAVACRIPT中怎么解码啊?从网上找了一些,不能用,特别是处理中文时。HELP ME!
- 关于串口通讯问题,很急,在线等!!!
- 高手:在JPanel上绘图,为了滚动加入到JScrollPane中,但JPanel不能重绘...
- java解决约瑟夫问题
- JDBC 如何获取某个查询花费的时间(最好是DB端读出来 误差小) 用的Oracle
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;public class MonitorConn implements ActionListener { public MainFrame mf = null;
public Thread cli = null; MonitorConn(MainFrame mf) {
this.mf = mf;
} @Override
public void actionPerformed(ActionEvent arg0) { if (MainFrame.bConnect) {
mf.disConnect();
mf.btn.setLabel("连接");
MainFrame.bConnect = false;
} else {
mf.strAdress = mf.textAdress.getText(); if(!isValid(mf.strAdress)){
mf.textShow.append("ip地址无效,请输入正确的ip地址!\n"); } else {
// 启动client>>>>>>>
cli = new Thread(new ClientThread(mf, mf.strAdress));
cli.start(); // 等待本地客户端启动,设置bConnect为true;
synchronized (this) {
try {
this.wait(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// synchronized(this){
// this.notify();
// }
// 设置连接按钮的Lable;
if (MainFrame.bConnect) {
mf.textShow.append("Connect \\" + mf.strAdress
+ " success!\n");
mf.btn.setLabel("断开连接");
} else {
mf.textShow.append("Connect \\" + mf.strAdress + " fail!\n");
} }
}
}/* public static boolean isValid(String strAddr) {
String substr = "";
int count = 0;
int i = 0;
char[] sa = strAddr.toCharArray();
for (i = 0; i < sa.length; i++) {
if (count != 3) {
if (sa[i] == '.') {
count++;
if (!isRange(substr)) {
return false;
}
substr = "";
}else{
substr += String.valueOf(sa[i]);
}
} else {
substr += String.valueOf(sa[i]);
}
}
if(!isRange(substr)) {
return false;
}
if (count != 3){
return false;
}
return true;
} public static boolean isRange(String substr) {
int subint = 0;
try{
subint = Integer.parseInt(substr);
}catch(NumberFormatException nfe){
//nfe.printStackTrace();
return false;
}
if ((subint <= 255) && (subint >= 0)) {
return true;
} else {
return false;
}
}*/
public static boolean isValid(String strAddr) {
String strIP = "((1[0-9]?[0-9]?)|(25[0-5])|(2[0-4]?[0-9]?)|([3-9][0-9]?))\\." +
"((1[0-9]?[0-9]?)|(25[0-5])|(2[0-4]?[0-9]?)|([3-9][0-9]?)|0)\\." +
"((1[0-9]?[0-9]?)|(25[0-5])|(2[0-4]?[0-9]?)|([3-9][0-9]?)|0)\\." +
"((1[0-9]?[0-9]?)|(25[0-5])|(2[0-4]?[0-9]?)|([3-9][0-9]?)|0)";
return strAddr.matches(strIP);
}
}//-----------------ClientThread.java----------------------//本地Client线程public class ClientThread implements Runnable {
public MainFrame mf = null;
public String adress = null; ClientThread(MainFrame mf, String adress){
this.mf = mf;
this.adress = adress;
}
@Override
public void run() {
MainFrame.bConnect = mf.connect(adress);
}
}//-----------------ServerThread--------------------//Server线程
import java.net.*;
import java.util.*;
import java.io.*;public class ServerThread implements Runnable {
public static String acceptStr = null;
public boolean bServerStart = false;
public MainFrame mf;
public ServerSocket ss = null;
public static List<Client> clients = new ArrayList<Client>();
ServerThread(MainFrame mf){
this.mf = mf;
//打开端口9999
try{
ss = new ServerSocket(9999);
bServerStart = true;
}catch(BindException be){
mf.textShow.append("端口绑定失败>>>>>\n");
mf.textShow.append("请关掉相关程序>>>>\n");
System.exit(0);
}catch(IOException e){
e.printStackTrace();
}
}
@Override
public void run() {
while(bServerStart){
try{
//mf.textShow.append("Server start>>>>>\n");
Socket s = ss.accept();
Client c = new Client(s, mf);
clients.add(c);
//mf.textShow.append("connect success>>>>>\n");
Thread t = new Thread(c);
t.start();
}catch(IOException e){
e.printStackTrace();
}
}
}}//--------------------------Client.java----------------------//server创建的外部线程
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
public class Client implements Runnable {
public Socket s = null;
public DataInputStream dis = null;
public boolean bConn = false;
public MainFrame mf = null;
InetSocketAddress isa = null;
Client(Socket s, MainFrame mf){
this.s = s;
this.mf = mf;
try{
dis = new DataInputStream(s.getInputStream());
}catch(IOException e){
e.printStackTrace();
}
bConn = true;
}
@Override
public void run() {
try{
while(bConn){
ServerThread.acceptStr = dis.readUTF();
isa = (InetSocketAddress)s.getRemoteSocketAddress();
mf.textShow.append(isa.getAddress() + ": " + ServerThread.acceptStr + "\n");
}
}catch(EOFException eofe){
ServerThread.clients.remove(this);
mf.textShow.append(isa.getAddress() + " exit>>>>>\n");
}catch(IOException e){
e.printStackTrace();
}finally{
try{
if(dis == null){
dis.close();
}
if(s == null){
s.close();
}
}catch(IOException ioe){
ioe.printStackTrace();
}
}
}
}
//------------------MonitorConn.java----------------------//响应连接按钮事件,使本地Client连接到远端Server
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;public class MonitorConn implements ActionListener { public MainFrame mf = null;
public Thread cli = null; MonitorConn(MainFrame mf) {
this.mf = mf;
} @Override
public void actionPerformed(ActionEvent arg0) { if (MainFrame.bConnect) {
mf.disConnect();
mf.btn.setLabel("连接");
MainFrame.bConnect = false;
} else {
mf.strAdress = mf.textAdress.getText(); if(!isValid(mf.strAdress)){
mf.textShow.append("ip地址无效,请输入正确的ip地址!\n"); } else {
// 启动client>>>>>>>
cli = new Thread(new ClientThread(mf, mf.strAdress));
cli.start(); // 等待本地客户端启动,设置bConnect为true;
synchronized (this) {
try {
this.wait(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// synchronized(this){
// this.notify();
// }
// 设置连接按钮的Lable;
if (MainFrame.bConnect) {
mf.textShow.append("Connect \\" + mf.strAdress
+ " success!\n");
mf.btn.setLabel("断开连接");
} else {
mf.textShow.append("Connect \\" + mf.strAdress + " fail!\n");
} }
}
}/* public static boolean isValid(String strAddr) {
String substr = "";
int count = 0;
int i = 0;
char[] sa = strAddr.toCharArray();
for (i = 0; i < sa.length; i++) {
if (count != 3) {
if (sa[i] == '.') {
count++;
if (!isRange(substr)) {
return false;
}
substr = "";
}else{
substr += String.valueOf(sa[i]);
}
} else {
substr += String.valueOf(sa[i]);
}
}
if(!isRange(substr)) {
return false;
}
if (count != 3){
return false;
}
return true;
} public static boolean isRange(String substr) {
int subint = 0;
try{
subint = Integer.parseInt(substr);
}catch(NumberFormatException nfe){
//nfe.printStackTrace();
return false;
}
if ((subint <= 255) && (subint >= 0)) {
return true;
} else {
return false;
}
}*/
public static boolean isValid(String strAddr) {
String strIP = "((1[0-9]?[0-9]?)|(25[0-5])|(2[0-4]?[0-9]?)|([3-9][0-9]?))\\." +
"((1[0-9]?[0-9]?)|(25[0-5])|(2[0-4]?[0-9]?)|([3-9][0-9]?)|0)\\." +
"((1[0-9]?[0-9]?)|(25[0-5])|(2[0-4]?[0-9]?)|([3-9][0-9]?)|0)\\." +
"((1[0-9]?[0-9]?)|(25[0-5])|(2[0-4]?[0-9]?)|([3-9][0-9]?)|0)";
return strAddr.matches(strIP);
}
}//-----------------ClientThread.java----------------------//本地Client线程public class ClientThread implements Runnable {
public MainFrame mf = null;
public String adress = null; ClientThread(MainFrame mf, String adress){
this.mf = mf;
this.adress = adress;
}
@Override
public void run() {
MainFrame.bConnect = mf.connect(adress);
}
}//-----------------ServerThread--------------------//Server线程
import java.net.*;
import java.util.*;
import java.io.*;public class ServerThread implements Runnable {
public static String acceptStr = null;
public boolean bServerStart = false;
public MainFrame mf;
public ServerSocket ss = null;
public static List<Client> clients = new ArrayList<Client>();
ServerThread(MainFrame mf){
this.mf = mf;
//打开端口9999
try{
ss = new ServerSocket(9999);
bServerStart = true;
}catch(BindException be){
mf.textShow.append("端口绑定失败>>>>>\n");
mf.textShow.append("请关掉相关程序>>>>\n");
System.exit(0);
}catch(IOException e){
e.printStackTrace();
}
}
@Override
public void run() {
while(bServerStart){
try{
//mf.textShow.append("Server start>>>>>\n");
Socket s = ss.accept();
Client c = new Client(s, mf);
clients.add(c);
//mf.textShow.append("connect success>>>>>\n");
Thread t = new Thread(c);
t.start();
}catch(IOException e){
e.printStackTrace();
}
}
}}//--------------------------Client.java----------------------//server创建的外部线程
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
public class Client implements Runnable {
public Socket s = null;
public DataInputStream dis = null;
public boolean bConn = false;
public MainFrame mf = null;
InetSocketAddress isa = null;
Client(Socket s, MainFrame mf){
this.s = s;
this.mf = mf;
try{
dis = new DataInputStream(s.getInputStream());
}catch(IOException e){
e.printStackTrace();
}
bConn = true;
}
@Override
public void run() {
try{
while(bConn){
ServerThread.acceptStr = dis.readUTF();
isa = (InetSocketAddress)s.getRemoteSocketAddress();
mf.textShow.append(isa.getAddress() + ": " + ServerThread.acceptStr + "\n");
}
}catch(EOFException eofe){
ServerThread.clients.remove(this);
mf.textShow.append(isa.getAddress() + " exit>>>>>\n");
}catch(IOException e){
e.printStackTrace();
}finally{
try{
if(dis == null){
dis.close();
}
if(s == null){
s.close();
}
}catch(IOException ioe){
ioe.printStackTrace();
}
}
}
}