【JAVA】socket 聊天系统

22 篇文章 0 订阅

参考:http://blog.csdn.net/xsc_c/article/details/12586985

 

服务器端工程:

开始界面(设置端口)——同客户端,只要port部分

package socketServer;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class StartServer extends JFrame implements ActionListener{
	JLabel portLabel=new JLabel("Port");
	JTextField portText=new JTextField(8);
	JButton start=new JButton("Start");
	JPanel mainPanel=new JPanel();
	
	public StartServer(){
		this.add(mainPanel);
		mainPanel.add(portLabel);
		mainPanel.add(portText);
		mainPanel.add(start);
		start.addActionListener(this);
		this.pack();
		this.setLocationRelativeTo(null);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setVisible(true);
	}
	
	public static void main(String[] args) {
		new StartServer();

	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		this.dispose();
		new Thread(new Runnable(){

            @Override
            public void run()
            {
                // TODO Auto-generated method stub
                new ServerView(Integer.parseInt(portText.getText()));
            }
		    
		}).start();
	}

}


 


聊天框

public class ServerView {
	JFrame frame=new JFrame("Server");
	JPanel mainPanel=new JPanel();
	JTextArea area=new JTextArea();
	JScrollPane scroll=new JScrollPane(area);
	JTextField input=new JTextField("Input ...");
	JButton sendButton=new JButton("Send");
	PrintWriter pw=null;
	int port=10000;
	
	public ServerView(int port){
		this.port=port<=1024?10000:port;
		
		input.addKeyListener(new SendListener());
		sendButton.addActionListener(new SendActionListener());
		sendButton.setMnemonic(KeyEvent.VK_ENTER);
		
		mainPanel.setLayout(null);
		mainPanel.add(scroll);
		mainPanel.add(input);
		mainPanel.add(sendButton);
		
		scroll.setBounds(15, 20, 200, 250);
		input.setBounds(15, 300, 200, 30);
		sendButton.setBounds(135, 350, 80, 20);
		
		frame.add(mainPanel);
		frame.setSize(250,430);
		frame.setLocationRelativeTo(null);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
		frame.setVisible(true);
		frame.setResizable(false);
		
		try {
			//服务器监听
			ServerSocket ss = new ServerSocket(this.port);
			//等待客户端连接
			Socket client = ss.accept();
			
			BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
			
			pw = new PrintWriter(client.getOutputStream(),true);
			
			String ip=client.getLocalAddress().getHostAddress();
			//读取从客户端发来的信息 
			while(true) {
				String info = br.readLine();
				showInfo("client"+ip,info);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	class SendListener implements KeyListener{

		@Override
		public void keyPressed(KeyEvent arg0) {
		}

		@Override
		public void keyReleased(KeyEvent arg0) {
		}

		@Override
		public void keyTyped(KeyEvent e) {
			if(e.getKeyChar()=='\n'){
				send(input.getText());
			}
			
		}
		
	}
	
	class SendActionListener implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent arg0) {
			send(input.getText());
		}
		
	}
	
	private void send(String s){
		
		if(s.equals("")){
			return;
		}
		
		String ip="server";
		try {
			ip+=InetAddress.getLocalHost().getHostAddress().toString();
		} catch (UnknownHostException e1) {
			e1.printStackTrace();
		} 
		showInfo(ip,s);
		pw.println(s);
		input.setText("");
	}
	
	private void showInfo(String name,String s){
		SimpleDateFormat sdf=new SimpleDateFormat("MM-dd kk:mm");
		area.append(name+" / "+sdf.format(new Date())+":\n");
		area.append(s+"\n");
		JScrollBar bar=scroll.getVerticalScrollBar();     
		bar.setValue(bar.getMaximum()+100);
	}
	
	public static void main (String[] args){
		new ServerView(10000);
	}
}


 

客户端工程:

开始界面(设置要连接的服务端IP,端口)

public class StartClient extends JFrame implements ActionListener{
	JLabel portLabel=new JLabel("Port ");
	JTextField portText=new JTextField(8);
	JLabel ipLabel=new JLabel("IP ");
	JTextField ipText=new JTextField(12);
	JButton start=new JButton("Start");
	JPanel mainPanel=new JPanel();
	
	public StartClient(){
		this.add(mainPanel);
		mainPanel.add(portLabel);
		mainPanel.add(portText);
		mainPanel.add(ipLabel);
		mainPanel.add(ipText);
		mainPanel.add(start);
		start.addActionListener(this);
		this.pack();
		this.setLocationRelativeTo(null);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setVisible(true);
	}
	
	public static void main(String[] args) {
		new StartClient();

	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		this.dispose();
		new Thread(new Runnable(){

            @Override
            public void run()
            {
                // TODO Auto-generated method stub
                new ClientView(ipText.getText(), Integer.parseInt(portText.getText()));
            }
		    
		}).start();
	}

}


聊天界面

public class ClientView {
	JFrame frame=new JFrame("Client");
	JPanel mainPanel=new JPanel();
	JTextArea area=new JTextArea();
	JScrollPane scroll=new JScrollPane(area);
	JTextField input=new JTextField("Input ...");
	JButton sendButton=new JButton("Send");
	PrintWriter pw=null;
	String ip=null;
	int port=10000;
	
	public ClientView(String ip,int port){
		input.addKeyListener(new SendListener());
		sendButton.addActionListener(new SendActionListener());
		sendButton.setMnemonic(KeyEvent.VK_ENTER);
		
		mainPanel.setLayout(null);
		mainPanel.add(scroll);
		mainPanel.add(input);
		mainPanel.add(sendButton);
		
		scroll.setBounds(15, 20, 200, 250);
		input.setBounds(15, 300, 200, 30);
		sendButton.setBounds(135, 350, 80, 20);
		
		frame.add(mainPanel);
		frame.setSize(250,430);
		frame.setLocationRelativeTo(null);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
		frame.setVisible(true);
		
		try {
			this.port=(port<=1024?10000:port);
			this.ip= (ip==null?InetAddress.getLocalHost().getHostAddress().toString():ip);
			
			Socket s = new Socket(this.ip,this.port);
			BufferedReader br = new BufferedReader
					(new InputStreamReader(s.getInputStream()));
			pw = new PrintWriter(s.getOutputStream(),true);
			while(true) {
				//不停的读取服务器端发来的信息
				String info = br.readLine();
				this.showInfo("server"+this.ip,info);
			}
		} catch (Exception e) {
		}
	}
	
	class SendListener implements KeyListener{

		@Override
		public void keyPressed(KeyEvent arg0) {
		}
		@Override
		public void keyReleased(KeyEvent arg0) {
		}
		@Override
		public void keyTyped(KeyEvent e) {
			if(e.getKeyChar()=='\n'){
				send(input.getText());
			}
			
		}
		
	}
	
	class SendActionListener implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent arg0) {
			send(input.getText());
		}
		
	}
	
	private void send(String s){
		
		if(s.equals("")){
			return;
		}
		
		String ip="client";
		try {
			ip+=InetAddress.getLocalHost().getHostAddress().toString();
		} catch (UnknownHostException e1) {
			e1.printStackTrace();
		} 
		showInfo(ip,s);
		pw.println(s);
		input.setText("");
	}
	
	private void showInfo(String name,String s){
		SimpleDateFormat sdf=new SimpleDateFormat("MM-dd kk:mm");
		area.append(name+" / "+sdf.format(new Date())+":\n");
		area.append(s+"\n");
		JScrollBar bar=scroll.getVerticalScrollBar();     
		bar.setValue(bar.getMaximum()+100);
	}
	
	public static void main (String[] args){
		new ClientView("10.135.86.58",10000);
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值