`
antjava
  • 浏览: 8799 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

java socket 二

    博客分类:
  • JAVA
阅读更多

借着上次回顾到socket的资料,这次完成一个c/s端的socket示例。主要回顾io、socket、swing、thread 。

下一个学习的重点是nio和mina框架,不知道各位同仁能否指点一二,或者在学习nio的时候有什么建议,或者学习的方法,谢谢大家了。

以前长期潜水,现在在写这些学生时代的代码,少不得拍砖,谢谢拍砖。



 

服务器端:

 

 

package com.jzpark.socket;

import java.awt.FileDialog;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import com.swtdesigner.SwingResourceManager;

/**
 * @author: antxuan
 * @createtime: 2010-5-29 下午08:40:18
 * @Description: socket客户端
 */
public class Server {
	private static final long serialVersionUID = 1L;

	JFrame jf = new JFrame("socket通信服务器端");
	// 在现人数
	// 连接到主机socket的ip地址列表
	// 客户端发送来的信息
	final JTextArea txtAMessage = new JTextArea();
	// 服务器端回复信息
	final JTextField txtRMessage = new JTextField();

	final JLabel lblMessage = new JLabel();

	// 得到操作系统平台下的文件分隔符
	final String separator = System.getProperty("line.separator");
	// 保存客户端发来的数据 记录ip地址和消息
	private List<String> list = new ArrayList<String>();
	
	SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd ss:hh:mm");
	SimpleDateFormat format2=new SimpleDateFormat("sshhmm");

	
	// 取得输入流
	DataInputStream dis = null;
	// 取得输出流
	DataOutputStream dos = null;

	// 服务器套接字
	ServerSocket serverSocket = null;
	// 套接字
	Socket socket = null;

	// 创建窗体
	private void createFrame() {

		jf.getContentPane().setLayout(null);
		jf.setSize(431, 395);
		JLabel jlmessage = new JLabel("当前连接服务器人数:");
		jf.add(jlmessage);

		final JLabel label = new JLabel();
		label.setBounds(35, 19, 66, 30);
		label.setText("启动状态:");
		jf.getContentPane().add(label);

		final JButton btnOn = new JButton();
		btnOn.setBounds(247, 20, 138, 29);
		btnOn.addActionListener(new ActionListener() {
			public void actionPerformed(final ActionEvent e) {
				// new ServerSocketThread();
				btnOn.setEnabled(false);

				new ServerSocketThread().start();   
				lblMessage.setText("已启动...");
				
				lblMessage.setIcon(SwingResourceManager.getIcon(Server.class, "ajax-loader.gif"));

				 
			}
		});
		btnOn.setText("启动服务器socket");
		jf.getContentPane().add(btnOn);

		final JLabel lblmessage = new JLabel();
		lblmessage.setName("");
		lblmessage.setText("");
		lblmessage.setBounds(292, 201, 66, 18);
		jf.getContentPane().add(lblmessage);

		final JLabel label_1 = new JLabel();
		label_1.setText("接收到的消息:");
		label_1.setBounds(10, 75, 91, 18);
		jf.getContentPane().add(label_1);

		txtAMessage.setEditable(false);
		txtAMessage.setBounds(107, 75, 278, 142);
		jf.getContentPane().add(txtAMessage);

		final JLabel label_3 = new JLabel();
		label_3.setText("回复信息:");
		label_3.setBounds(10, 256, 66, 18);
		jf.getContentPane().add(label_3);

		txtRMessage.setBounds(107, 254, 278, 22);
		jf.getContentPane().add(txtRMessage);

		lblMessage.setText("");
		lblMessage.setBounds(107, 15, 91, 39);
		jf.getContentPane().add(lblMessage);

		final JButton button_1 = new JButton();
		button_1.addActionListener(new ActionListener() {
			public void actionPerformed(final ActionEvent e) {
				
//				if(socket.isBound()){
//					JOptionPane.showMessageDialog(jf,"没有连接!:");
//
//				}
				
				String message = txtRMessage.getText();
				if(message.equals("")){
					JOptionPane.showMessageDialog(jf, "请输入回复信息");
					return;
				}
				// 当点击发送按钮后,将发送消息框清空
				txtRMessage.setText("");
				try {
					String date=format.format(new Date());
					txtAMessage.append(date+"您的回复:" + message + separator);
					dos.writeUTF(message );
					dos.flush();

				} catch (IOException e1) {

					e1.printStackTrace();
				}
			}
		});
		button_1.setText("发送");
		button_1.setBounds(152, 305, 102, 29);
		jf.getContentPane().add(button_1);

		final JButton btnClose = new JButton();
		btnClose.setText("关闭socket");
		btnClose.setBounds(23, 305, 102, 28);
		jf.getContentPane().add(btnClose);

		btnClose.addActionListener(new ActionListener() {
			public void actionPerformed(final ActionEvent e) {
				// ServerSockets sc=new ServerSockets(new Socket());
				btnOn.setEnabled(true);
				btnClose.setEnabled(false);
				lblMessage.setText("已关闭!");

				if (socket != null) {
					if (!socket.isClosed()) {
						try {
							socket.close();
						} catch (IOException e1) {
							e1.printStackTrace();
						}
					}
				}

			}
		});

		// 禁止用户设置窗体大小
		jf.setResizable(false);
		jf.addWindowListener(new WindowListener() {
			public void windowActivated(WindowEvent e) {
			}

			public void windowClosed(WindowEvent e) {
			}

			public void windowClosing(WindowEvent e) {
				Runtime.getRuntime().exit(0);
				try {
					if(socket!=null){
						if(!socket.isClosed()){
							socket.close();
						}
					}
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}

			public void windowDeactivated(WindowEvent e) {
			}

			public void windowDeiconified(WindowEvent e) {
			}

			public void windowIconified(WindowEvent e) {
			}

			public void windowOpened(WindowEvent e) {
			}
		});
		jf.show();

		final JButton button_1_1 = new JButton();
		button_1_1.addActionListener(new ActionListener() {
			public void actionPerformed(final ActionEvent e) {
				FileDialog fd=new FileDialog(jf,"保存聊天信息",FileDialog.SAVE );		   
 				fd.show();
				byte[] b= txtAMessage.getText().getBytes();
				try {
					String fileName=fd.getDirectory()+fd.getFile()+format2.format(new Date())+".txt"; 
					FileOutputStream fos=new FileOutputStream(fileName);
					fos.write(b);
					JOptionPane.showMessageDialog(jf, "对话信息已经保存在"+fileName+"中");
				} catch (FileNotFoundException e1) {
 					e1.printStackTrace();
				} catch (IOException e1) {
 					e1.printStackTrace();
				}
				
			}
		});
		button_1_1.setText("导出信息");
		button_1_1.setBounds(283, 305, 102, 29);
		jf.getContentPane().add(button_1_1);
	}

	class ServerSocketThread extends Thread {

		public void run() {
			try {
				serverSocket = new ServerSocket(3333);
				while (true) {
					socket = serverSocket.accept();
					dis = new DataInputStream(socket.getInputStream());
					dos = new DataOutputStream(socket.getOutputStream());
					txtAMessage.append(socket.getLocalAddress() + "说:"
							+ dis.readUTF() + separator);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {

		Server server = new Server();
		server.createFrame();
	}

}

 

客户端:

 

    package com.jzpark.socket;

 

import java.awt.FileDialog;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

/**
 * @author: antxuan
 * @createtime: 2010-5-29 下午08:40:11
 * @Description: socket服务器端
 */
public class Client {
	static JFrame jf = new JFrame();
	// 聊天记录
	final JTextArea txtARecode = new JTextArea();
	//发送消息
	final JTextField txtRMessage = new JTextField();
	// 得到操作系统平台下的文件分隔符
	final String separator = System.getProperty("line.separator");	
	//套接字
	private  Socket socket=null;
	// 取得输入流
	DataInputStream dis = null;
	// 取得输出流
	DataOutputStream dos = null;
	//ip地址
	String address;
	//端口
	int port;

	SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd ss:hh:mm");
	 
	SimpleDateFormat format2=new SimpleDateFormat("sshhmm");

	
	// 构建窗体
	public Client() {

		jf.setSize(440, 375);
		jf.getContentPane().setLayout(null);
		jf.setTitle("socket客户端连接工具");

		final JLabel label = new JLabel();
		label.setText("IP地址:");
		label.setBounds(26, 10, 50, 18);
		jf.getContentPane().add(label);

		final JLabel label_1 = new JLabel();
		label_1.setText("端口号:");
		label_1.setBounds(26, 34, 59, 18);
		jf.getContentPane().add(label_1);

		final JTextField txtAddress = new JTextField();
		txtAddress.setBounds(82, 8, 152, 22);
		jf.getContentPane().add(txtAddress);

		final JTextField txtPort = new JTextField();
		txtPort.setBounds(82, 32, 152, 22);
		jf.getContentPane().add(txtPort);

		final JButton btnConnect = new JButton(); 
		btnConnect.addActionListener(new ActionListener() {
			public void actionPerformed(final ActionEvent e) {
				
				//为ip地址和端口赋值 
				
				address=txtAddress.getText(); 
				if(address.equals("")){
					JOptionPane.showMessageDialog(jf,"请输入ip地址如:10.1.110.4");
					return;
				}
				try {
					if(txtPort.getText().equals("")){
						JOptionPane.showMessageDialog(jf,"请输入端口号");
						return;
					}
					port=Integer.parseInt(txtPort.getText());

				} catch (NumberFormatException e2) {
					JOptionPane.showMessageDialog(jf,"端口号必须为数字");
					return;
				}
				
				
				// 创建连接
				new ClientSocketThread().start();
				JOptionPane.showMessageDialog(jf,"已经连接到"+address+"的"+port+"端口");

				
			}
		});
		btnConnect.setText("连接");
		btnConnect.setBounds(292, 29, 87, 28);
		jf.getContentPane().add(btnConnect);

		final JLabel label_2 = new JLabel();
		label_2.setText("发送消息:");
		label_2.setBounds(10, 253, 66, 18);
		jf.getContentPane().add(label_2);

		txtRMessage.setBounds(82, 251, 297, 22);
		jf.getContentPane().add(txtRMessage);

		final JButton button = new JButton();
		button.addActionListener(new ActionListener() {
			public void actionPerformed(final ActionEvent e) {
				
				//取得发送信息
				String message=txtRMessage.getText();
				txtRMessage.setText("");
				if(message.equals("")){
					JOptionPane.showMessageDialog(jf,"发送消息不能为空");
					return;
				}
				
				String date=format.format(new Date());
				
				txtARecode.append(date+"您说:"+message+separator); 
				
				try {
					dos.writeUTF(message);
				} catch (IOException e1) {
 					e1.printStackTrace();
				}

			}
		});
		button.setText("发送");
		button.setBounds(100, 307, 87, 28);
		jf.getContentPane().add(button);

		final JLabel label_3 = new JLabel();
		label_3.setText("聊天记录:");
		label_3.setBounds(10, 73, 66, 18);
		jf.getContentPane().add(label_3);

		txtARecode.setBounds(82, 73, 297, 148);
		txtARecode.setAutoscrolls(true);
		jf.getContentPane().add(txtARecode);

		final JButton button_1 = new JButton(); 
		button_1.addActionListener(new ActionListener() {
			public void actionPerformed(final ActionEvent e) {
				FileDialog fd=new FileDialog(jf,"保存聊天信息",FileDialog.SAVE );		   
 				fd.show();
				String message=txtARecode.getText();
 				try { 
 					String fileName=fd.getDirectory()+fd.getFile()+format2.format(new Date())+".txt"; 
 					FileOutputStream fos = new FileOutputStream(fileName);
					fos.write(message.getBytes());
					JOptionPane.showMessageDialog(jf,"对话信息已经保存在"+fileName+"中");
				} catch (FileNotFoundException e1) { 
 					e1.printStackTrace();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				 
			}
		});
		button_1.setText("导出聊天记录");
		button_1.setBounds(218, 307, 125, 28);
		jf.getContentPane().add(button_1); 

		txtARecode.setEditable(false);
		
		jf.setResizable(false);
		jf.setLocation(220, 220);

		jf.show();
		
		jf.addWindowListener(new WindowListener() {
			public void windowActivated(WindowEvent e) {
			}

			public void windowClosed(WindowEvent e) {
			}

			public void windowClosing(WindowEvent e) {
				Runtime.getRuntime().exit(0);
				try {
					if(socket!=null){
						if(!socket.isClosed()){
							socket.close();
						}
					}
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}

			public void windowDeactivated(WindowEvent e) {
			}

			public void windowDeiconified(WindowEvent e) {
			}

			public void windowIconified(WindowEvent e) {
			}

			public void windowOpened(WindowEvent e) {
			}
		});
		
	}

	public static void main(String[] args) {
		new Client();
	}
	
	
	class ClientSocketThread extends Thread {

		public void run() {
			try {
				 
				while (true) {
					 socket=new Socket(address,port);
					 dis = new DataInputStream(socket.getInputStream());
					 dos = new DataOutputStream(socket.getOutputStream());
					 //服务器端返回数据
					 String message=dis.readUTF();
					 txtARecode.append("服务器返回:"+message+separator);
				}
			} catch (Exception e) {
				e.printStackTrace();
				JOptionPane.showMessageDialog(jf,"不能连接目标主机或端口:"+e.getMessage());
				try {
					if(socket!=null){
						if(!socket.isClosed()){
							socket.close();
						}
					}
 				} catch (IOException e1) {
 					e1.printStackTrace();
				}
			}
		}
	}
}
 
  • 大小: 12.6 KB
  • 大小: 12.7 KB
1
2
分享到:
评论
4 楼 mercyblitz 2010-06-01  
antjava 写道
mercyblitz 写道
楼主加油咯,这个BIO的实现,可以添加尝试Thread Pool,更好的服务端管理。

你好!虚心请教,什么是bio,
接下来我可能会用mina实现这个demo,
当然后期主要是如何管理连接,维护连接等。



BIO,Blocking IO,阻塞IO
3 楼 antjava 2010-06-01  
mercyblitz 写道
楼主加油咯,这个BIO的实现,可以添加尝试Thread Pool,更好的服务端管理。

你好!虚心请教,什么是bio,
接下来我可能会用mina实现这个demo,
当然后期主要是如何管理连接,维护连接等。
2 楼 mercyblitz 2010-05-31  
楼主加油咯,这个BIO的实现,可以添加尝试Thread Pool,更好的服务端管理。
1 楼 antjava 2010-05-31  
补充:JTextArea 增加滚动条。

final JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(80, 75, 297, 162);
jf.getContentPane().add(scrollPane);

txtARecode.setAutoscrolls(true);
scrollPane.setViewportView(txtARecode);

相关推荐

    java socket教程java socket教程

    二、Socket类和ServerSocket类 1. ServerSocket类:用于创建服务器端Socket,它监听指定的端口,当有客户端连接时,会返回一个Socket对象用于通信。 2. Socket类:表示客户端到服务器的连接。它封装了输入/输出流,...

    JAVA Socket 经典教程

    - **字节流与字符流**:Java提供了处理二进制数据的InputStream/OutputStream和处理文本数据的Reader/Writer。根据数据类型选择合适的流进行操作。 4. **异常处理** - **网络异常**:网络通信中可能出现...

    java socket 视频流转发socket

    Java Socket是Java编程语言中用于网络通信的核心API,它提供了低级别的、面向连接的、基于TCP/IP协议的网络通信能力。在"Java Socket 视频流转发Socket"这个主题中,我们将深入探讨如何使用Java Socket来处理视频流...

    JAVA Socket编程实现文件上传

    Java Socket编程是网络编程的基础,它提供了在两个应用程序之间建立通信连接的能力。在这个场景中,我们讨论的是如何使用Java的Socket来实现文件上传功能,即从客户端将文件发送到服务器,然后保存到服务器的数据库...

    java socket客户端断线重连

    java socket client 断线重连的简单实现 有什么意见可以提哦

    Java Socket 聊天通信演示代码

    Java Socket 是一种网络通信协议,它是Java编程语言中实现客户端-服务器模型的基础。Socket 提供了低级别的、面向连接的、双向通信的网络接口,允许应用程序通过网络进行数据传输。在本示例中,我们将深入探讨Java ...

    java socket使用加密协议传输对象

    ### Java Socket 使用加密协议传输对象:深入解析与实践 在当今互联网时代,数据安全成为企业和个人用户关注的焦点。在Java开发中,Socket编程是一种常见的网络通信方式,它允许不同计算机上的应用程序通过网络进行...

    java socket连接池 实现

    2. 获取连接:当应用程序需要建立Socket连接时,从连接池中获取一个闲置的Socket,如果没有,则等待直到有连接被归还或达到最大等待时间。 3. 使用连接:应用程序使用获取到的Socket进行网络通信。 4. 归还连接:...

    java socket 客户端代码

    在Java编程语言中,Socket是实现网络通信的基础组件,它为两台计算机之间的通信提供了低级别的接口。在本文中,我们将深入探讨Java Socket客户端代码及其在创建基于Socket的聊天室客户端中的应用。 首先,理解...

    java socket实现smtp发送邮件,支持SSL

    Java Socket 实现 SMTP 发送邮件是一项常见的编程任务,尤其在自动化通知、系统间通信或用户交互中非常有用。SMTP(Simple Mail Transfer Protocol)是互联网上用于传输电子邮件的标准协议,而Java Socket则是Java...

    java socket 经典版本

    Java Socket编程是网络编程的基础,它是Java API提供的一种用于实现客户端-服务器通信的接口。在Java中,Socket类和ServerSocket类是进行网络通信的核心组件。这个经典版本可能包含了一系列关于如何有效使用Java ...

    java socket源码解析

    java socket源码解析 java socket源码解析 java socket源码解析 java socket源码解析

    Java Socket 实现SMTP邮件发送,支持SSL/TSL

    Java Socket编程是Java网络编程的基础,它提供了网络通信的能力,使得程序可以与其他计算机上的服务进行交互。在本案例中,我们将关注如何使用Java Socket来实现SMTP(Simple Mail Transfer Protocol)邮件发送,并...

    java socket 用户真实IP测试

    在Java网络编程中,Socket是实现客户端与服务器端通信的基础组件。当涉及到通过代理服务器或者负载均衡器(如Nginx)进行TCP转发时,获取用户的真实IP地址可能会变得复杂。在标题“java socket nginx tcp转发 用户...

    java socket 中文教程

    Java Socket是Java编程语言中用于网络通信的核心API,它提供了低级别的、面向连接的、基于TCP/IP协议的网络通信服务。本教程将深入探讨Java Socket的相关知识点,旨在帮助开发者理解和掌握如何在Java环境中构建网络...

    Java Socket网络编程.pdf

    2. 打开Socket的输入/输出流:获取Socket的I/O流,为数据传输做好准备。 3. 数据读写:通过输入流读取数据,通过输出流写入数据。 4. 关闭流和Socket:通信完成后,关闭流和Socket以释放系统资源。 Java的Socket...

    Java socket编程实现两台主机间的通信

    二、Java Socket 编程的实现方法 Java Socket 编程的实现方法可以分为四步: 1. 打开一个 Socket 连接:在客户端,使用 Socket 类来建立连接,并指定主机名和端口号。在服务器端,使用 ServerSocket 类来监听...

    通过java socket实现屏幕网络监控

    Java Socket技术是网络编程中的重要组成部分,主要用于实现两个应用程序之间的通信。在这个场景中,我们讨论的是如何使用Java Socket来实现实时的屏幕监控功能,即服务端能够远程查看客户端的屏幕内容,这样的功能在...

Global site tag (gtag.js) - Google Analytics