您的位置:首页 > 理论基础 > 计算机网络

【java学习记录】12.用Socket网络访问方法,实现简单的网络聊天程序

2016-12-06 14:22 1286 查看
设计网络聊天程序,实现如下功能:

(1)聊天两端具有相同的界面,包括能输入消息的文本框、发送消息按钮、消息列表文本框;

(2)任意一端均可以实时发送和接收消息,并在自身的消息列表中显示消息记录。

ClientThread

public class ClientThread extends Thread{//客户端线程

Socket client;
ClientFrame frame;

@Override
public void run() {
// TODO Auto-generated method stub
try {
//读取服务器端数据   
DataInputStream dis=new DataInputStream(client.getInputStream());
InputStreamReader isr = new InputStreamReader(dis);
   BufferedReader br = new BufferedReader(isr);
   while (true) {
    String read = br.readLine();
       frame.receiveText.append("服务端:" + read + "\n");
   }

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

ClientFrame

public class ClientFrame implements ActionListener{//客户端界面

JFrame clientF=new JFrame();//窗口
Panel panel=new Panel();//面板
Label titleLab=new Label();//标签
Label ipLab=new Label();
Label portLab=new Label();
TextField ipText=new TextField();//存储ip地址
TextField portText=new TextField();//存储端口号
TextArea receiveText=new TextArea();//接收框
TextArea sendText=new TextArea();//发送框
Button connectBtn=new Button("连接");//“连接”按钮
Button sendBtn=new Button("发送");//“发送”按钮
Socket client;
boolean press=true;//判断是否连接

ClientFrame(){
//创建客户端窗口
clientF.setTitle("客户端");//窗口标题
clientF.setSize(500, 500);//设置大小
clientF.setVisible(true);//设置显示
clientF.setLocationRelativeTo(null);//窗体居中
clientF.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//结束进程

//创建面板
panel.setBackground(Color.pink);
panel.setLayout(null);//取消默认布局
clientF.add(panel);

//创建标签
titleLab.setText("客户端程序");
ipLab.setText("IP:");
portLab.setText("Port:");
titleLab.setFont(new Font("宋体",1,20));//设置字体
ipLab.setFont(new Font("",1,15));
portLab.setFont(new Font("",1,15));
titleLab.setBounds(clientF.size().width/2-55, 10, 110, 50);//设置大小和位置
ipLab.setBounds(60, 70, 25, 20);
portLab.setBounds(ipLab.getX()+220, ipLab.getY(), 40, ipLab.size().height);

// titleLab.setBackground(Color.yellow);//设置背景颜色

// ipLab.setBackground(Color.yellow);

// portLab.setBackground(Color.yellow);
panel.add(titleLab);//添加到面板
panel.add(ipLab);
panel.add(portLab);

//ip地址、端口号文本框
ipText.setBounds(ipLab.getX()+ipLab.size().width, ipLab.getY(), 100, ipLab.size().height);
portText.setBounds(portLab.getX()+portLab.size().width, portLab.getY(), 100, portLab.size().height);

// try {//获取本地ip地址

// ipText.setText(InetAddress.getLocalHost().getHostAddress());

// } catch (UnknownHostException e) {//抛出异常

// // TODO Auto-generated catch block

// }
ipText.setText("127.0.0.1");
portText.setText("2013");//设置端口号
ipText.setEnabled(false);//文本框不可用
portText.setEnabled(false);
panel.add(ipText);
panel.add(portText);

//接收、发送框
receiveText.setBounds(ipLab.getX(), ipLab.getY()+ipLab.size().height+10, portText.getX()-ipLab.getX()+100, 200);
sendText.setBounds(receiveText.getX(), receiveText.getY()+receiveText.size().height+10, receiveText.size().width, 70);
receiveText.setEditable(false);//接收框不可编辑
panel.add(receiveText);
panel.add(sendText);

//按钮
connectBtn.setBounds(titleLab.getX()-60, sendText.getY()+sendText.size().height+20, 60, 40);
sendBtn.setBounds(titleLab.getX()+titleLab.size().width, connectBtn.getY(), connectBtn.size().width, connectBtn.size().height);
connectBtn.setFont(new Font("", 0, 16));
sendBtn.setFont(new Font("", 0, 16));
panel.add(connectBtn);
panel.add(sendBtn);
//添加监听器
connectBtn.addActionListener(this);
sendBtn.addActionListener(this);

}

//点击事件
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub

if(e.getSource()==connectBtn){

// System.out.println("111");
String ip=ipText.getText();
int port=Integer.parseInt(portText.getText());
try {//连接服务器
client=new Socket(ip, port);//创建一个流套接字并将其连接到指定主机上的指定端口号 
if(press){
receiveText.append("与服务器连接成功!\n");press=false;
}else{
receiveText.append("已连接!\n");
}
ClientThread ct = new ClientThread();
   ct.client = client;
   ct.frame = this;
   ct.start();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}else{

// System.out.println("222");
try {
//向服务器端发送数据  
     PrintStream ps = new PrintStream(client.getOutputStream());
     ps.println(sendText.getText());
     receiveText.append("客户端:"+sendText.getText()+"\n");
     this.sendText.setText("");
}catch (IOException ex) {
}
}
}

// public static void main(String[] args) {

// new ClientFrame();

// }

}



Client


public class Client {//客户端
Client() {
ClientFrame frame = new ClientFrame();
}
public static void main(String[] args) {
new Client();
}

}



ServerFrame


public class ServerFrame implements ActionListener{//服务器端界面

JFrame serverF=new JFrame();//窗口
Panel panel=new Panel();//面板
Label titleLab=new Label();//标签
TextArea receiveText=new TextArea();//接收框
TextArea sendText=new TextArea();//发送框
Button sendBtn=new Button("发送");//“发送”按钮
Socket server;

ServerFrame(){
//创建客户端窗口
serverF.setTitle("服务器端");//窗口标题
serverF.setSize(500, 450);//设置大小
serverF.setVisible(true);//设置显示
serverF.setLocationRelativeTo(null);//窗体居中
serverF.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//结束进程

//创建面板
panel.setBackground(Color.pink);
panel.setLayout(null);//取消默认布局
serverF.add(panel);

//创建标签
titleLab.setText("服务器端程序");
titleLab.setFont(new Font("宋体",1,20));//设置字体
titleLab.setBounds(serverF.size().width/2-65, 10, 130, 50);//设置大小和位置

// titleLab.setBackground(Color.yellow);//设置背景颜色
panel.add(titleLab);//添加到面板

//接收、发送框
receiveText.setBounds(60, 70, serverF.size().width-120, 200);
sendText.setBounds(receiveText.getX(), receiveText.getY()+receiveText.size().height+10, receiveText.size().width-100, 70);
receiveText.setEditable(false);//接收框不可编辑
panel.add(receiveText);
panel.add(sendText);

//按钮
sendBtn.setBounds(receiveText.getX()+receiveText.size().width-80, sendText.getY(), 80, sendText.size().height);
sendBtn.setFont(new Font("", 0, 16));
panel.add(sendBtn);
//添加监听器
sendBtn.addActionListener(this);
}

//点击事件
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub

// System.out.println("333");
try {
//向客户端发送数据  
     PrintStream ps = new PrintStream(server.getOutputStream());//server.getOutputStream():获取服务器端的输出流
     ps.println(sendText.getText());
     receiveText.append("服务端:"+sendText.getText()+"\n");
     this.sendText.setText("");
}catch (IOException ex) {
}
}

// public static void main(String[] args) {

// new ServerFrame();

// }

}

Server


public class Server {//服务器端

static ServerFrame frame;
Server() {
frame = new ServerFrame();
}
public static void main(String[] args) {
   new Server();
   try {
     ServerSocket ss = new ServerSocket(2013);//根据端口号,接收客户端连接
     Socket server = ss.accept();//侦听并接受到此端口号的连接
     frame.server = server;
     frame.receiveText.append("与客户端连接成功!\n");
     //读取客户端数据   
     DataInputStream dis = new DataInputStream(server.getInputStream());
     InputStreamReader isr = new InputStreamReader(dis);
     BufferedReader br = new BufferedReader(isr);
     while(true)
     {
       String read = br.readLine();
       frame.receiveText.append("客户端:" + read + "\n");
     }
   }catch (IOException ex) {
   }
}

}









内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐