java网络通信技术示例:简单的聊天小程序

  再学习完java的通信技术后,做了一个简单的窗体聊天程序。程序非常简单,主要目的是当练习巩固自己所学的东西,在这里写出来记录以下。下面直接上代码。

首先是服务端代码:

package ChatTwoPackage;

import java.io.*;
import java.net.*;

public class ChatTwoServer {
	
	public ChatTwoServer(int port,String name) throws IOException
	{
		ServerSocket server=new ServerSocket(port);//创建seversocket对象,提供tcp连接服务。指定端口port,等待tcp连接。
		System.out.print("正在等待连接,请勿操作!");
		Socket client=server.accept();//创建socket对象,它等待接收客户端的连接。
		new ChatTwoClient(name,client);//实现图形界面。
		server.close();
	}

	public static void main(String[] args) throws IOException {
		new ChatTwoServer(2001,"SQ");

	}

}

然后是客户端的代码:

package ChatTwoPackage;

import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.io.*;

public class ChatTwoClient extends JFrame implements ActionListener {
	private String name;
	private JTextArea text_re;
	private JTextField text_se;
	private PrintWriter cout;
	private JButton buttons[];
	public ChatTwoClient(String name,Socket socket) throws IOException
	{
		super("我:"+name+InetAddress.getLocalHost().getHostAddress()+":"+socket.getLocalPort());
		this.setBounds(320, 240, 400, 240);
		this.text_re=new JTextArea();
		this.text_re.setEditable(false);
		this.getContentPane().add(new JScrollPane(this.text_re));
		
		JToolBar toolBar=new JToolBar();
		this.getContentPane().add(toolBar,"South");
		toolBar.add(this.text_se=new JTextField(30));
		buttons=new JButton[2];
		buttons[0]=new JButton("发送");
		buttons[1]=new JButton("下线");
		toolBar.add(buttons[0]);
		toolBar.add(buttons[1]);
		buttons[0].addActionListener(this);
		buttons[1].addActionListener(this);//给按钮添加事件监听,委托当前对象处理
		this.setVisible(true);
		this.name=name;
		this.cout=new PrintWriter(socket.getOutputStream(),true);//获得socket输出流
		this.cout.println(name);
		BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream())); //将socket的字节输入流转换为字符流,默认GBK字符集,再创建缓冲字符输入流
                String line="连接"+br.readLine()+"成功";
                while(line!=null&&!line.endsWith("bye"))
		{
			text_re.append(line+"\r\n");
			line=br.readLine();
		}//读取对方发送的内容并显示,直到内容为为空或对方下线
		br.close();
		this.cout.close();
		socket.close();
		buttons[0].setEnabled(false);
		buttons[1].setEnabled(false);
	}
	public ChatTwoClient(String name,String host,int port) throws IOException
	{
		this(name,new Socket(host,port));//调用另一个构造方法
	}
	public void actionPerformed(ActionEvent ev)
	{
		if(ev.getActionCommand().equals("发送"))
		{
			this.cout.println(name+":"+text_se.getText());
			text_re.append("我:"+text_se.getText()+"\n");
			text_se.setText("");
		}//按下发送按钮后,将内容发出,并更新自己聊天框的内容
		if(ev.getActionCommand().equals("下线"))
		{
			text_re.append("你已下线\n");
			this.cout.println(name+"离线\n"+"bye\n");
			buttons[0].setEnabled(false);
			buttons[1].setEnabled(false);
		}//下线按钮按下后,发送bye作为下线标记
	}
	

	public static void main(String[] args) throws IOException {
		new ChatTwoClient("mxl","127.0.0.1",2001); //ip地址和端口

	}

}

运行效果:


说明:

1.两台计算机一台作为服务端,作为服务端的计算机需要有两个代码。首先运行服务端的代码,等待客户端机器连接,客户端运行客户端代码后,提示连接成功。就可以发送信息了。

2.运行代码前需要将ip地址改为自己计算机当前的ip地址(Modem、ISDN、ADSL、有线宽频、小区宽频等方式上网的计算机,每次上网所分配到的IP地址都不相同,这称为动态IP地址)。如果要用一台计算机充当客户端和服务端,就将ip地址写为:127.0.0.1(127.0.0.1是回送地址,指本地机,一般用来测试使用)。先运行服务端代码,再运行客户端代码即可。

猜你喜欢

转载自blog.csdn.net/xlantian/article/details/80441216