文档库 最新最全的文档下载
当前位置:文档库 › Java网络编程代码

Java网络编程代码

Java网络编程代码
Java网络编程代码

例10-1 Test.java

import https://www.wendangku.net/doc/238093588.html,.*;

import java.io.*;

import java.util.Date;

class Test{

public static void main(String args[]) throws Exception{

int c;

URL hp=new URL("https://www.wendangku.net/doc/238093588.html,/");

URLConnection hpCon=hp.openConnection();

System.out.println("Date: "+new Date(hpCon.getDate()));

System.out.println("Content-Type: "+hpCon.getContentType());

System.out.println("Expires: "+hpCon.getExpiration());

System.out.println("Last-Modified: "+new Date(hpCon.getLastModified()));

int len=hpCon.getContentLength();

System.out.println("Content-Length: "+len);

if(len>0){

System.out.println("=== Content ===");

InputStream input=hpCon.getInputStream();

int i=len;

while(((c=input.read())!=-1)&&(--i>0)){

System.out.print((char)c);

}

input.close();

}else{

System.out.println("No Content Available");

}

}

}

例10-2 Client.java

import java.io.*;

import https://www.wendangku.net/doc/238093588.html,.*;

public class Client{

public static void main(String args[]){

String s=null;

Socket socket;

DataInputStream in=null;

DataOutputStream out=null;

try{

socket=new Socket("localhost",4331);

in=new DataInputStream(socket.getInputStream());

out=new DataOutputStream(socket.getOutputStream());

out.writeUTF("Hello!It's Client");

while(true){

s=in.readUTF();

out.writeUTF(":"+Math.random());

System.out.println("Client get:"+s);

Thread.sleep(2000);

}

}catch(IOException e){

System.out.println("can't connect");

}catch(InterruptedException e){}

}

}

例10-3 Server.java

import java.io.*;

import https://www.wendangku.net/doc/238093588.html,.*;

public class Server{

public static void main(String args[]){

ServerSocket server=null;

Socket socket=null;

String s=null;

DataOutputStream out=null;

DataInputStream in=null;

try{

server=new ServerSocket(4331);

}catch(IOException e1){

System.out.println("ERROR:"+e1);

}

try{

socket=server.accept();

in=new DataInputStream(socket.getInputStream());

out=new DataOutputStream(socket.getOutputStream());

while(true){

s=in.readUTF();

out.writeUTF("It's Server:");

out.writeUTF("Client sends:"+s);

System.out.println("Server gets:"+s);

Thread.sleep(2000);

}

}catch(IOException e){

System.out.println(""+e);

}catch(InterruptedException e){}

}

例10-4 WriteServer.java

import https://www.wendangku.net/doc/238093588.html,.*;

class WriteServer{

public static int serverPort=19777;

public static int clientPort=4662;

public static int buffer_size=1024;

public static DatagramSocket ds;

public static byte buffer[]=new byte[buffer_size];

public static void TheServer() throws Exception{

int pos=0;

while(true){

int c=System.in.read();

switch(c){

case -1:

System.out.println("Server Quits.");

return;

case '\n':

ds.send(new DatagramPacket(buffer,pos,InetAddress.getLocalHost(), clientPort));

pos=0;

break;

default:

buffer[pos++]=(byte)c;

}

}

}

public static void main(String args[]) throws Exception{

ds=new DatagramSocket(serverPort);

TheServer();

}

}

//WriteClient

import https://www.wendangku.net/doc/238093588.html,.*;

class WriteClient{

public static int clientPort=4662;

public static int buffer_size=1024;

public static DatagramSocket ds;

public static byte buffer[]=new byte[buffer_size];

public static void TheClient() throws Exception{

while(true){

DatagramPacket p=new DatagramPacket(buffer,buffer.length);

ds.receive(p);

System.out.println(new String(p.getData(),0,p.getLength()));

}

}

public static void main(String args[]) throws Exception{

ds=new DatagramSocket(clientPort);

TheClient();

}

}

例10-5 MCServer.java

import java.io.*;

import https://www.wendangku.net/doc/238093588.html,.*;

class MCServer{

public static void main(String[] args) throws IOException{

System.out.println("Server starting...\n");

MulticastSocket s=new MulticastSocket();

InetAddress group=InetAddress.getByName("231.0.0.1");

byte[] dummy=new byte[0];

DatagramPacket dgp=new DatagramPacket(dummy,0,group,10000);

for(int i=0;i<30000;i++){

byte[] buffer=("Video line "+i).getBytes();

dgp.setData(buffer);

dgp.setLength(buffer.length);

s.send(dgp);

}

s.close();

}

}

// MCClient.java

import java.io.*;

import https://www.wendangku.net/doc/238093588.html,.*;

class MCClient{

public static void main(String[] args) throws IOException{

MulticastSocket s=new MulticastSocket(10000);

InetAddress group=InetAddress.getByName("231.0.0.1");

s.joinGroup(group);

for(int i=0;i<10;i++){

byte[] buffer=new byte[256];

DatagramPacket dgp=new DatagramPacket(buffer,buffer.length);

s.receive(dgp);

byte[] buffer2=new byte[dgp.getLength()];

System.arraycopy(dgp.getData(),0,buffer2,0,dgp.getLength());

System.out.println(new String(buffer2));

}

s.leaveGroup(group);

s.close();

}

}

例题10-1 聊天程序

客户端代码Client.java

package client;

import javax.swing.UIManager;

public class Client{

public Client(){

Frame1 frame=new Frame1();

frame.setVisible(true);

frame.validate();

}

public static void main(String[] args){

try{

UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

}catch(Exception e){

e.printStackTrace();

}

new Client();

}

}

客户端代码Frame1.java

package client;

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import https://www.wendangku.net/doc/238093588.html,.*;

import java.io.*;

public class Frame1 extends JFrame implements Runnable{

private JPanel contentPane;

private TextArea textArea1=new TextArea();

private Label label1=new Label();

private JTextField textField1=new JTextField();

private JButton button1=new JButton();

private JButton button2=new JButton();

private JButton button3=new JButton();

Socket socket=null;

BufferedReader in=null;

PrintWriter out=null;

JTextField server=new JTextField();

JLabel jLabel1=new JLabel();

JLabel jLabel2=new JLabel();

JTextField port=new JTextField();

JScrollPane jScrollPane1=new JScrollPane();

JList jList1=new JList();

JLabel jLabel3=new JLabel();

DefaultListModel l1=new DefaultListModel();

public Frame1(){

try{

init();

}catch(Exception e){

e.printStackTrace();

}

}

private void init() throws Exception{

server.setText(InetAddress.getLocalHost().getHostAddress());

server.setBounds(new Rectangle(69,252,74,22));

contentPane=(JPanel)this.getContentPane();

textArea1.setEditable(false);

textArea1.setFont(new java.awt.Font("Dialog",Font.PLAIN,14));

textArea1.setBounds(new Rectangle(11,9,383,199));

contentPane.setLayout(null);

this.setSize(new Dimension(506,314));

this.setTitle("客户端");

label1.setFont(new java.awt.Font("Dialog",Font.PLAIN,12));

label1.setText("消息:");

label1.setBounds(new Rectangle(26,213,32,27));

button1.setActionCommand("发送");

button1.setBounds(new Rectangle(334,216,62,23));

button1.setEnabled(false);

button1.setFont(new java.awt.Font("Dialog",Font.PLAIN,12)); button1.setText("发送");

button1.addActionListener(new java.awt.event.ActionListener(){ public void actionPerformed(ActionEvent e){

button1_actionPerformed(e);

}

});

button2.setBounds(new Rectangle(266,251,58,24));

button2.setFont(new java.awt.Font("Dialog",Font.PLAIN,12)); button2.setText("连接");

button2.addActionListener(new java.awt.event.ActionListener(){ public void actionPerformed(ActionEvent e){

button2_actionPerformed(e);

}

});

button3.setBounds(new Rectangle(333,251,62,22));

button3.setFont(new java.awt.Font("Dialog",Font.PLAIN,12)); button3.setText("退出");

button3.addActionListener(new java.awt.event.ActionListener(){ public void actionPerformed(ActionEvent e){

button3_actionPerformed(e);

}

});

jLabel1.setFont(new java.awt.Font("Dialog",Font.PLAIN,12)); jLabel1.setToolTipText("");

jLabel1.setHorizontalAlignment(SwingConstants.RIGHT); jLabel1.setHorizontalTextPosition(SwingConstants.RIGHT); jLabel1.setText("服务器:");

jLabel1.setBounds(new Rectangle(11,254,58,20));

jLabel2.setFont(new java.awt.Font("Dialog",Font.PLAIN,12)); jLabel2.setToolTipText("");

jLabel2.setHorizontalAlignment(SwingConstants.RIGHT); jLabel2.setHorizontalTextPosition(SwingConstants.RIGHT); jLabel2.setText("端口:");

jLabel2.setBounds(new Rectangle(172,253,27,18));

port.setText("8000");

port.setBounds(new Rectangle(202,251,40,22));

jList1.setFont(new java.awt.Font("Dialog",Font.PLAIN,12)); jLabel3.setBounds(new Rectangle(406,254,91,21));

textField1.setBounds(new Rectangle(58,215,271,24)); jScrollPane1.setBounds(new Rectangle(404,14,94,226)); jScrollPane1.getViewport().add(jList1);

contentPane.add(button3,null);

contentPane.add(button2,null);

contentPane.add(button1,null);

contentPane.add(server,null);

contentPane.add(jLabel1,null);

contentPane.add(textField1,null);

contentPane.add(textArea1,null);

contentPane.add(jLabel2,null);

contentPane.add(port,null);

contentPane.add(label1,null);

contentPane.add(jScrollPane1,null);

contentPane.add(jLabel3,null);

jList1.setModel(l1);

}

void button1_actionPerformed(ActionEvent e){

out.println(jLabel3.getText()+"对"

+l1.getElementAt(jList1.getSelectedIndex())+"说:"+textField1.getText());

out.flush();

textField1.setText("");

}

void button3_actionPerformed(ActionEvent e){

try{

out.println("大家尽情聊,再见!");

out.flush();

}catch(Exception e2){}

finally{

System.exit(0);

}

}

void button2_actionPerformed(ActionEvent e){

Thread thread=new Thread(this);

thread.start();

}

public void run(){

try{

socket=new Socket(server.getText(),Integer.parseInt(port.getText()));

in=new BufferedReader(new InputStreamReader(socket.getInputStream()));

out=new PrintWriter(socket.getOutputStream());

button1.setEnabled(true);

receiver r=new receiver();

Thread t=new Thread(r);

t.start();

textArea1.append("欢迎加入聊天室\n");

button2.setEnabled(false);

}catch(Exception e){

textArea1.append("连接失败!请确认服务器地址并且服务器已启动\n");

}

}

private class receiver implements Runnable{

public void run(){

String s1=null;

try{

s1=in.readLine();

while(s1!=null){

if(s1.equals("Clear users!")){

l1.removeAllElements();

l1.addElement("大家");

jList1.setSelectedIndex(0);

}else if(jLabel3.getText().equals("")){

jLabel3.setText(s1);

}else if(s1.length()<8&&!jLabel3.getText().equals(s1)){

l1.addElement(s1);

}else if(!jLabel3.getText().equals(s1)){

textArea1.append(s1+"\n");

}

s1=in.readLine();

}

in.close();

out.close();

socket.close();

}catch(Exception e){}

button1.setEnabled(false);

}

}

}

服务器端代码

package server;

import https://www.wendangku.net/doc/238093588.html,.*;

import java.io.*;

public class ServerThread implements Runnable{

ServerSocket server=null;

BufferedReader in=null;

PrintWriter out=null;

InetAddress myServer=null;

Object users[]=new Object[1000];

static int userCount=0;

public ServerThread(){

try{

init();

}catch(Exception e){

e.printStackTrace();

}

}

private void init() throws Exception{

Thread thread=new Thread(this);

thread.start();

}

public void run(){

try{

server=new ServerSocket(8000);

Socket socket;

while(true){

socket=server.accept();

// 这里一直等待如果连接成功,则创建了本机通信的套接层

if(socket!=null){

// 新用户连接成功

users[userCount]=socket;

Receiver r=new Receiver(socket,userCount);

// 创建接收线程

Thread t=new Thread(r);

// 创建接收线程

t.start();

userCount++;

}

}

}catch(Exception e){

e.printStackTrace();

}

}

private class Receiver implements Runnable{

Socket socket;

int user;

Receiver(Socket socket,int user){

this.socket=socket;

https://www.wendangku.net/doc/238093588.html,er=user;

}

public void run(){

BufferedReader in=null;

PrintWriter out=null;

String s1=null;

int userNo;

try{

out=new PrintWriter(socket.getOutputStream());

// 通知所有客户新用户的到来

out.println("user"+user);

// 让对方知道自己的名字

out.flush();

for(int j=0;j

// 对所有的用户发送

if(users[j]==null)

continue;

out=new PrintWriter(((Socket)users[j]).getOutputStream());

// 通知所有客户新用户的到来

out.println("Clear users!");

// 让对方刷新自己的列表

out.flush();

for(int k=0;k

out.println("user"+k);

// 让大家知道自己的名字

out.flush();

}

}

in=new BufferedReader(new InputStreamReader(socket.getInputStream()));

s1=in.readLine();

while(!s1.equals("大家尽情聊,再见!")){

// 必须是死循环方式接收,否则丢失数据!

int temp=s1.indexOf("对");

int temp1=s1.indexOf("说");

String tempS=s1.substring(temp+1,temp1);

if(tempS.equals("大家")){

for(int j=0;j

// 对所有的用户发送

if(users[j]==null)

continue;

out=new PrintWriter(((Socket)users[j]).getOutputStream());

// 通知所有客户新用户的到来

out.println(s1);

// 让对方刷新自己的列表

out.flush();

}

}else{

try{

userNo=Integer.parseInt(tempS.substring(4));

out=new PrintWriter(((Socket)users[userNo]).getOutputStream());

// 通知所有客户新用户的到来

out.println(s1);

// 发送给指定的用户

out.flush();

}catch(Exception e){}

}

s1=in.readLine();

// 接收当前缓存数据

}

System.out.print("User go");

in.close();

out.close();

socket.close();

}catch(Exception e){}

}

}

public static void main(String[] args){

new ServerThread();

}

}

例题10-2 本例用Java实现了一个简易的IE浏览器,不支持Script语言。其中利用JeditPane的setPage()方法显示页面

import java.io.IOException;

import https://www.wendangku.net/doc/238093588.html,.URL;

import javax.swing.*;

import javax.swing.event.*;

import java.awt.*;

import java.awt.event.*;

public class HtmlBrowser extends JFrame{

JPanel contentPane; // 包含整个框架的容器

BorderLayout layout=new BorderLayout();

JLabel jLabelPrompt=new JLabel(); // 状态提示框

JPanel jPanelMain=new JPanel();

BorderLayout borderLayoutMain=new BorderLayout();

JTextField urlInput=new JTextField(); // URL输入框

JEditorPane webPane=new JEditorPane(); // 显示网页内容的容器

public HtmlBrowser(){ // 定义构造方法

try{

init(); // 初始化并显示界面

}catch(Exception e){

e.printStackTrace();

}

}

private void init() throws Exception{ // 界面初始化

contentPane=(JPanel)getContentPane();

contentPane.setLayout(layout);

jPanelMain.setLayout(borderLayoutMain);

jLabelPrompt.setText("请输入URL");

urlInput.setText(""); // 清空文本框

urlInput.addActionListener(new java.awt.event.ActionListener(){

public void actionPerformed(ActionEvent e){

textFieldURL_actionPerformed(e);

}

});

webPane.setEditable(false); // 设置不可编辑

webPane.addHyperlinkListener(new javax.swing.event.HyperlinkListener(){ public void hyperlinkUpdate(HyperlinkEvent e){

webUpdate(e);

}

});

JScrollPane scrollPane=new JScrollPane();

scrollPane.getViewport().add(webPane);

jPanelMain.add(urlInput,"North");

jPanelMain.add(scrollPane,"Center");

contentPane.add(jLabelPrompt,"North");

contentPane.add(jPanelMain,"Center");

enableEvents(AWTEvent.WINDOW_EVENT_MASK);

this.setSize(new Dimension(600,500));

this.setTitle("迷你IE ");

this.setVisible(true);

}

void textFieldURL_actionPerformed(ActionEvent e){ // 输入地址后响应回车try{

webPane.setPage(urlInput.getText()); // 显示URL

}catch(IOException ex){

JOptionPane.showMessageDialog(this,"URL地址不正确:"+urlInput.getText(), "输入不正确!",0);

}

}

void webUpdate(HyperlinkEvent e){ // 响应页面打开超链接消息

if(e.getEventType()==javax.swing.event.HyperlinkEvent.EventType.ACTIVATED){ try{

URL url=e.getURL(); // 从消息中得到URL

webPane.setPage(url); // 显示页面内容

urlInput.setText(url.toString()); // 显示URL

}catch(IOException io){

JOptionPane.showMessageDialog(this,"打开该链接失败!","输入不正确!",0);

}

}

}

protected void processWindowEvent(WindowEvent e){ // 处理窗体事件

super.processWindowEvent(e);

if(e.getID()==WindowEvent.WINDOW_CLOSING){

System.exit(0); // 关闭

}

}

public static void main(String[] args){

new HtmlBrowser();

}

}

相关文档