import java.io.InputStream;
創(chuàng)新互聯(lián)是一家專注網(wǎng)站建設(shè)、網(wǎng)絡(luò)營(yíng)銷策劃、微信小程序開(kāi)發(fā)、電子商務(wù)建設(shè)、網(wǎng)絡(luò)推廣、移動(dòng)互聯(lián)開(kāi)發(fā)、研究、服務(wù)為一體的技術(shù)型公司。公司成立10余年以來(lái),已經(jīng)為超過(guò)千家成都會(huì)所設(shè)計(jì)各業(yè)的企業(yè)公司提供互聯(lián)網(wǎng)服務(wù)。現(xiàn)在,服務(wù)的超過(guò)千家客戶與我們一路同行,見(jiàn)證我們的成長(zhǎng);未來(lái),我們一起分享成功的喜悅。
import java.io.DataInputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.DataOutputStream;
import java.io.BufferedReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;
import java.util.Date;
class Server
{
public Server()
{
try
{
ServerSocket s=new ServerSocket(8888);
Socket ss=s.accept();
OutputStream out=ss.getOutputStream();
DataOutputStream dout=new DataOutputStream(out);
InputStream in=ss.getInputStream();
DataInputStream din=new DataInputStream(in);
System.out.print(din.readUTF()+"!");
dout.writeUTF("你已經(jīng)連接到服務(wù)器"+"\t"+"你的地址:"+ss.getInetAddress()+"\t"
+"你的鏈接端口:"+ss.getLocalPort()+"\n");
new ReadMessage(din).start();
new SendMessage(dout).start();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
new Server();
}
}
//接受客戶端信息
class ReadMessage extends Thread
{
private DataInputStream din;
public ReadMessage(DataInputStream din)
{
this.din=din;
}
public void run()
{
String str;
try
{
while (true)
{
str=din.readUTF();
System.out.println(new Date().toLocaleString()+"客戶端說(shuō):"+str);
if (str.equals("bye"))
{
System.out.println("客戶端下線!");
break;
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
// 發(fā)出服務(wù)器信息
class SendMessage extends Thread
{
private DataOutputStream dout;
public SendMessage(DataOutputStream dout)
{
this.dout=dout;
}
public void run()
{
InputStreamReader inr=new InputStreamReader(System.in);
BufferedReader buf=new BufferedReader(inr);
String str;
try
{
while(true)
{
str=buf.readLine();
dout.writeUTF(str);
if (str.equals("bye"))
{
System.out.println("服務(wù)器退出!");
System.exit(1);
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
import java.io.InputStream;
import java.io.DataInputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.DataOutputStream;
import java.io.BufferedReader;
import java.net.Socket;
import java.io.IOException;
import java.util.Date;
class Client
{
public Client()
{
try
{
Socket s=new Socket("192.168.1.2",8888);
InputStream in=s.getInputStream();
DataInputStream din=new DataInputStream(in);
OutputStream out=s.getOutputStream();
DataOutputStream dout=new DataOutputStream(out);
dout.writeUTF("服務(wù)器你好!我是客戶端");
System.out.println(din.readUTF());
new Thread(new SenderMessage(dout)).start();
new Thread(new ReaderMessage(din)).start();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
new Client();
}
}
class ReaderMessage implements Runnable
{
private DataInputStream din;
public ReaderMessage(DataInputStream din)
{
this.din=din;
}
public void run()
{
String str;
try
{
while(true)
{
str=din.readUTF();
System.out.println(new Date().toLocaleString()+"服務(wù)器說(shuō):"+str);
if (str.equals("bye"))
{
System.out.println("服務(wù)器已經(jīng)關(guān)閉,此程序自動(dòng)退出!");
break;
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
class SenderMessage implements Runnable
{
private DataOutputStream dout;
public SenderMessage(DataOutputStream dout)
{
this.dout=dout;
}
public void run()
{
String str;
InputStreamReader inf=new InputStreamReader(System.in);
BufferedReader buf=new BufferedReader(inf);
try
{
while (true)
{
str=buf.readLine();
dout.writeUTF(str);
if (str.equals("bye"))
{
System.out.println("客戶端自己退出!");
System.exit(1);
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.io.*;
public class ClientDemo01 {
public static void main(String[] args){
JFrame f=new JFrame("AA");
JPanel p1=new JPanel();
JPanel p2=new JPanel();
JTextArea ta=new JTextArea(15,30);
ta.setEditable(false); //文本域只讀
JScrollPane sp=new JScrollPane(ta); //滾動(dòng)窗格
JTextField tf=new JTextField(20);
JButton b=new JButton("發(fā)送");
p1.add(sp);
p2.add(tf);
p2.add(b);
f.add(p1,"Center");
f.add(p2,"South");
f.setBounds(300,300,360,300);
f.setVisible(true);
f.setResizable(false);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Socket socket=null;
BufferedInputStream bis=null;
BufferedOutputStream bos=null;
try{
socket=new Socket("192.168.0.4",5000);
bis=new BufferedInputStream(socket.getInputStream());
bos=new BufferedOutputStream(socket.getOutputStream());
MyThread01 mt=new MyThread01(bis,ta);
mt.start();
}catch(Exception e){
e.printStackTrace();
}
b.addActionListener(new ButtonActionListener01(tf,ta,bos));
}
}
class ButtonActionListener01 implements ActionListener{
JTextField tf;
JTextArea ta;
BufferedOutputStream bos;
public ButtonActionListener01(JTextField tf,JTextArea ta,BufferedOutputStream bos){
this.tf=tf;
this.ta=ta;
this.bos=bos;
}
public void actionPerformed(ActionEvent e){
String message=tf.getText();
if(!message.equals("")){
tf.setText(""); //清空文本框
ta.append("AA:"+message+"\n"); //添加到文本域并換行
try{
bos.write(message.getBytes());
bos.flush();
}catch(Exception ex){
System.out.println("發(fā)送失敗");
}
}
}
}
class MyThread01 extends Thread{
BufferedInputStream bis;
JTextArea ta;
public MyThread01(BufferedInputStream bis,JTextArea ta){
this.bis=bis;
this.ta=ta;
}
public void run(){
try{
while(true){
byte[] b=new byte[100];
int length=bis.read(b);
String message=new String(b,0,length);
ta.append("BB:"+message+"\n");
}
}catch(Exception e){
e.printStackTrace();
}
}
} import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.io.*;
public class ServerDemo01{
public static void main(String[] args){
JFrame f=new JFrame("BB");
JPanel p1=new JPanel();
JPanel p2=new JPanel();
JTextArea ta=new JTextArea(12,30); //文本域,第一個(gè)參數(shù)為行數(shù),第二個(gè)參數(shù)為列數(shù)
ta.setEditable(false); //文本域只讀
JScrollPane sp=new JScrollPane(ta); //滾動(dòng)窗格
JTextField tf=new JTextField(20);
JButton b=new JButton("發(fā)送");
p1.add(sp);
p2.add(tf);
p2.add(b);
f.add(p1,"Center");
f.add(p2,"South");
f.setBounds(300,300,360,300);
f.setVisible(true);
f.setResizable(false);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ServerSocket server=null;
Socket socket=null;
BufferedInputStream bis=null;
BufferedOutputStream bos=null;
try{
server=new ServerSocket(5000);
//ta.append("等待AA連接...\n");
socket=server.accept();
//ta.append("AA已連接\n");
bis=new BufferedInputStream(socket.getInputStream());
bos=new BufferedOutputStream(socket.getOutputStream());
MyThread1 mt=new MyThread1(bis,ta);
mt.start();
}catch(Exception e){
e.printStackTrace();
}
b.addActionListener(new ButtonActionListener1(tf,ta,bos));
}
}
class ButtonActionListener1 implements ActionListener{
JTextField tf;
JTextArea ta;
BufferedOutputStream bos;
public ButtonActionListener1(JTextField tf,JTextArea ta,BufferedOutputStream bos){
this.tf=tf;
this.ta=ta;
this.bos=bos;
}
public void actionPerformed(ActionEvent e){
String message=tf.getText(); //獲取文本框中的內(nèi)容
if(!message.equals("")){
tf.setText(""); //清空文本框
ta.append("BB:"+message+"\n"); //添加到文本域并換行
try{
bos.write(message.getBytes());
bos.flush();
}catch(Exception ex){
System.out.println("發(fā)送失?。?);
}
}
}
}
class MyThread1 extends Thread{
BufferedInputStream bis;
JTextArea ta;
public MyThread1(BufferedInputStream bis,JTextArea ta){
this.bis=bis;
this.ta=ta;
}
public void run(){
try{
while(true){
byte[] b=new byte[100];
int length=bis.read(b);
String message=new String(b,0,length);
ta.append("AA:"+message+"\n");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
package com.kum.im.hrserver.test;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.awt.*;
import java.awt.event.*;
public class ChatClient {
private SocketChannel sc = null;
private String name = null;
private Frame f;
private TextArea ta;
private TextField tf;
private boolean runnable = true;
public static void main(String[] args){
ChatClient cc = new ChatClient();
cc.createUI();
cc.inputName();
cc.connect();
new ReceiveThread(cc,cc.getTextArea()).start();
}
public SocketChannel getSc(){
return sc;
}
public void setName(String name){
this.name = name;
}
public TextArea getTextArea(){
return ta;
}
public TextField getTextField(){
return tf;
}
public boolean getRunnable(){
return runnable;
}
public void stop(){
runnable = false;
}
public void shutDown(){
try{
sc.write(ByteBuffer.wrap("bye".getBytes("UTF-8")));
ta.append("Exit in 5 seconds!");
this.stop();
Thread.sleep(5000);
sc.close();
}catch(Exception e){
e.printStackTrace();
}
System.exit(0);
}
public void createUI(){
f = new Frame("Client");
ta = new TextArea();
ta.setEditable(false);
tf = new TextField();
Button send = new Button("Send");
Panel p = new Panel();
p.setLayout(new BorderLayout());
p.add(tf,"Center");
p.add(send,"East");
f.add(ta,"Center");
f.add(p,"South");
MyClientListener listener = new MyClientListener(this);
send.addActionListener(listener);
tf.addActionListener(listener);
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
ChatClient.this.shutDown();
}
});
f.setSize(400,400);
f.setLocation(600,0);
f.setVisible(true);
tf.requestFocus();
}
public boolean connect(){
try{
sc = SocketChannel.open();
//"zlg"為目標(biāo)計(jì)算機(jī)名
InetSocketAddress isa = new InetSocketAddress("192.168.1.43",8814);
sc.connect(isa);
sc.configureBlocking(false);
sc.write(ByteBuffer.wrap(name.getBytes("UTF-8")));
}catch(Exception e){
e.printStackTrace();
}
return true;
}
public void inputName(){
String name = javax.swing.JOptionPane.showInputDialog("Input Your Name:");
this.setName(name);
f.setTitle(name);
}
}
class MyClientListener implements ActionListener{
private ChatClient client;
public MyClientListener(ChatClient client){
this.client = client;
}
public void actionPerformed(ActionEvent e){
TextField tf = client.getTextField();
String info = tf.getText();
if(info.equals("bye")){
client.shutDown();
}else{
try{
client.getSc().write(ByteBuffer.wrap(info.getBytes("UTF-8")));
}catch (Exception e1) {
e1.printStackTrace();
}
}
tf.setText("");
tf.requestFocus();
}
}
class ReceiveThread extends Thread{
private ChatClient client;
private TextArea ta;
public ReceiveThread(ChatClient client,TextArea ta){
this.client = client;
this.ta = ta;
}
public void run(){
SocketChannel sc = client.getSc();
ByteBuffer byteBuffer = ByteBuffer.allocate(2048);
CharBuffer charBuffer = null;
Charset charset = Charset.forName("UTF-8");
CharsetDecoder decoder = charset.newDecoder();
String msg = null;
int n = 0;
try{
while(client.getRunnable()){
n = sc.read(byteBuffer);
if(n0){
byteBuffer.flip();
charBuffer = decoder.decode(byteBuffer);
msg = charBuffer.toString();
ta.append(msg + "\n");
}
byteBuffer.clear();
Thread.sleep(500);
}
}catch(Exception e){
e.printStackTrace();
System.exit(0);
}
}
}
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.net.*;
import java.util.*;
public class ICQServer {
private Selector selector = null;
private ServerSocketChannel ssc = null;
//服務(wù)器端通信端口號(hào)
private int port = 8814;
//在線用戶列表
private HashtableString, SocketChannel userList = null;
public ICQServer() {}
public ICQServer(int port) {
this.port = port;
}
//初始化服務(wù)器
public void init() {
try {
//創(chuàng)建選擇器對(duì)象
selector = Selector.open();
//創(chuàng)建ServerSocketChannel
ssc = ServerSocketChannel.open();
//設(shè)置ServerSocketChannel為非阻塞模式
ssc.configureBlocking(false);
InetAddress ip = InetAddress.getLocalHost();
System.out.println("主機(jī)地址 -------- " + ip);
InetSocketAddress isa = new InetSocketAddress(ip, port);
//將與本通道相關(guān)的服務(wù)器套接字對(duì)象綁定到指定地址和端口
ssc.socket().bind(isa);
//創(chuàng)建在線用戶列表
userList = new HashtableString, SocketChannel ();
}
catch (IOException e) {
System.out.println("初始化服務(wù)器時(shí)異常,原因 -------- " + e.getMessage());
}
}
//啟動(dòng)服務(wù)器
public void start() {
try {
//將ServerSocketChannel注冊(cè)到Selector上,準(zhǔn)備接收新連接請(qǐng)求
SelectionKey acceptKey = ssc.register(selector, SelectionKey.OP_ACCEPT);
SocketChannel sc;
int n;
String name; //用戶名
String msg; //用戶發(fā)言信息
while (true) {
//選擇當(dāng)前所有處于就緒狀態(tài)的通道所對(duì)應(yīng)的選擇鍵,并將這些鍵組成已選擇鍵集
n = selector.select(); //n為已選擇鍵集中鍵的個(gè)數(shù)
if (n 0) {
//獲取此選擇器的已選擇鍵集。
Set readyKeys = selector.selectedKeys();
Iterator it = readyKeys.iterator();
//遍歷當(dāng)前已選擇鍵集
while (it.hasNext()) {
SelectionKey key = (SelectionKey) it.next();
//從當(dāng)前已選擇鍵集中移除當(dāng)前鍵,避免重復(fù)處理
it.remove();
//如果當(dāng)前鍵對(duì)應(yīng)的通道已準(zhǔn)備好接受新的套接字連接
if (key.isAcceptable()) {
//獲取當(dāng)前鍵對(duì)應(yīng)的可選擇通道(ServerSocketChannel)
ssc = (ServerSocketChannel) key.channel();
//接收新的套接字連接請(qǐng)求,返回新建的SocketChannel
sc = (SocketChannel) ssc.accept();
//如果有新用戶接入
if (sc != null) {
//接收新上線用戶姓名
name = readMessage(sc);
//設(shè)置新建的SocketChannel為非阻塞模式
sc.configureBlocking(false);
//將新建的SocketChannel注冊(cè)到Selector上,準(zhǔn)備進(jìn)行數(shù)據(jù)"寫"操作,
//并將當(dāng)前用戶名以附件的方式附帶記錄到新建的選擇鍵上。
SelectionKey newKey = sc.register(selector,
SelectionKey.OP_WRITE, name);
//將新上線用戶信息加入到在線用戶列表
userList.put(name, sc);
//發(fā)送"新用戶上線"通知
transmitMessage(name + " in!", "--Server Info--");
}
}
//否則,如果當(dāng)前鍵對(duì)應(yīng)的通道已準(zhǔn)備好進(jìn)行"寫"操作
else if (key.isWritable()) {
//獲取當(dāng)前鍵對(duì)應(yīng)的可選擇通道(SocketChannel)
sc = (SocketChannel) key.channel();
//接收該通道相應(yīng)用戶的發(fā)言信息
msg = readMessage(sc);
//獲取選擇鍵上附帶記錄的當(dāng)前用戶名
name = key.attachment().toString();
//如果用戶提出要下線
if (msg.equals("bye")) {
//從在線用戶列表中移除當(dāng)前用戶
userList.remove(name);
//注銷當(dāng)前選擇鍵對(duì)應(yīng)的注冊(cè)關(guān)系
key.cancel();
//關(guān)閉當(dāng)前可選擇通道
sc.close();
//發(fā)送"用戶下線"通知
transmitMessage(name + " out!", "--Server Info--");
}
//否則,如果接收到的用戶發(fā)言信息非空("")
else if (msg.length() 0) {
//轉(zhuǎn)發(fā)用戶發(fā)言信息
transmitMessage(msg, name);
}
}
}
}
//延時(shí)循環(huán),降低服務(wù)器端處理負(fù)荷
Thread.sleep(500);
}
}
catch (Exception e) {
System.out.println("啟動(dòng)服務(wù)器時(shí)異常,原因 -------- " + e.getMessage());
}
}
//轉(zhuǎn)發(fā)用戶發(fā)言信息
public void transmitMessage(String msg, String name) {
try {
ByteBuffer buffer = ByteBuffer.wrap( (name + ":" + msg).getBytes("UTF-8"));
//將字節(jié)數(shù)組包裝到緩沖區(qū)中
Collection channels = userList.values();
SocketChannel sc;
for (Object o : channels) {
sc = (SocketChannel) o;
sc.write(buffer);
//將緩沖區(qū)數(shù)據(jù)寫入聊天面板(TextArea)
buffer.flip();
//將緩沖區(qū)ByteBuffer的極限值設(shè)置為當(dāng)前數(shù)據(jù)實(shí)際大小,將緩沖區(qū)的值設(shè)置為0
}
}
catch (Exception e) {
System.out.println("轉(zhuǎn)發(fā)用戶發(fā)言信息時(shí)異常,原因 -------- " + e.getMessage());
}
}
//接收用戶發(fā)言信息
public String readMessage(SocketChannel sc) {
String result = null;
int n = 0;
ByteBuffer buf = ByteBuffer.allocate(1024);
try {
n = sc.read(buf);
buf.flip();
Charset charset = Charset.forName("UTF-8");
CharsetDecoder decoder = charset.newDecoder();
CharBuffer charBuffer = decoder.decode(buf);
result = charBuffer.toString();
}
catch (IOException e) {
System.out.println("接收用戶發(fā)言信息時(shí)異常,原因 -------- " + e.getMessage());
}
return result;
}
public static void main(String args[]) {
ICQServer server = new ICQServer();
server.init();
server.start();
}
}
/**
* 基于UDP協(xié)議的聊天程序
*
* 2007.9.18
* */
//導(dǎo)入包
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.net.*;
public class Chat extends JFrame implements ActionListener
{
//廣播地址或者對(duì)方的地址
public static final String sendIP = "172.18.8.255";
//發(fā)送端口9527
public static final int sendPort = 9527;
JPanel p = new JPanel();
List lst = new List(); //消息顯示
JTextField txtIP = new JTextField(18); //填寫IP地址
JTextField txtMSG = new JTextField(20); //填寫發(fā)送消息
JLabel lblIP = new JLabel("IP地址:");
JLabel lblMSG = new JLabel("消息:");
JButton btnSend = new JButton("發(fā)送");
byte [] buf;
//定義DatagramSocket的對(duì)象必須進(jìn)行異常處理
//發(fā)送和接收數(shù)據(jù)報(bào)包的套接字
DatagramSocket ds = null;
//=============構(gòu)造函數(shù)=====================
public Chat()
{
CreateInterFace();
//注冊(cè)消息框監(jiān)聽(tīng)器
txtMSG.addActionListener(this);
btnSend.addActionListener(this);
try
{
//端口:9527
ds =new DatagramSocket(sendPort);
}
catch(Exception ex)
{
ex.printStackTrace();
}
//============接受消息============
//匿名類
new Thread(new Runnable()
{
public void run()
{
byte buf[] = new byte[1024];
//表示接受數(shù)據(jù)報(bào)包
while(true)
{
try
{
DatagramPacket dp = new DatagramPacket(buf,1024,InetAddress.getByName(txtIP.getText()),sendPort);
ds.receive(dp);
lst.add("【消息來(lái)自】◆" + dp.getAddress().getHostAddress() + "◆"+"【說(shuō)】:" + new String (buf,0,dp.getLength()) /*+ dp.getPort()*/,0);
}
catch(Exception e)
{
if(ds.isClosed())
{
e.printStackTrace();
}
}
}
}
}).start();
//關(guān)閉窗體事件
this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent w)
{
System.out.println("test");
int n=JOptionPane.showConfirmDialog(null,"是否要退出?","退出",JOptionPane.YES_NO_OPTION);
if(n==JOptionPane.YES_OPTION)
{
dispose();
System.exit(0);
ds.close();//關(guān)閉ds對(duì)象//關(guān)閉數(shù)據(jù)報(bào)套接字
}
}
});
}
//界面設(shè)計(jì)布局
public void CreateInterFace()
{
this.add(lst,BorderLayout.CENTER);
this.add(p,BorderLayout.SOUTH);
p.add(lblIP);
p.add(txtIP);
p.add(lblMSG);
p.add(txtMSG);
p.add(btnSend);
txtIP.setText(sendIP);
//背景顏色
lst.setBackground(Color.yellow);
//JAVA默認(rèn)風(fēng)格
this.setUndecorated(true);
this.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
this.setSize(600,500);
this.setTitle("〓聊天室〓");
this.setResizable(false);//不能改變窗體大小
this.setLocationRelativeTo(null);//窗體居中
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
this.setVisible(true);
txtMSG.requestFocus();//消息框得到焦點(diǎn)
}
//===============================Main函數(shù)===============================
public static void main(String[]args)
{
new Chat();
}
//================================發(fā)送消息===============================
//消息框回車發(fā)送消息事件
public void actionPerformed(ActionEvent e)
{
//得到文本內(nèi)容
buf = txtMSG.getText().getBytes();
//判斷消息框是否為空
if (txtMSG.getText().length()==0)
{
JOptionPane.showMessageDialog(null,"發(fā)送消息不能為空","提示",JOptionPane.WARNING_MESSAGE);
}
else{
try
{
InetAddress address = InetAddress.getByName(sendIP);
DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName(txtIP.getText()),sendPort);
ds.send(dp);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
txtMSG.setText("");//清空消息框
//點(diǎn)發(fā)送按鈕發(fā)送消息事件
if(e.getSource()==btnSend)
{
buf = txtMSG.getText().getBytes();
try
{
DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName(txtIP.getText()),sendPort);
}
catch(Exception ex)
{
ex.printStackTrace();
}
txtMSG.setText("");//清空消息框
txtMSG.requestFocus();
}
}
}