我是靠谱客的博主 烂漫手机,最近开发中收集的这篇文章主要介绍Java上机实验 Java中的网络编程1、读取服务器端文件2、会结帐的服务器3、读取服务器端的窗口4、与服务器玩猜字游戏5、传输图像,觉得挺不错的,现在分享给大家,希望可以做个参考。
概述
目录
- 1、读取服务器端文件
- 2、会结帐的服务器
- 2.1客户端模板
- 2.2服务器端模板
- 3、读取服务器端的窗口
- 3.1客户端模板
- 3.2服务器端模板
- 4、与服务器玩猜字游戏
- 4.1客户端模板
- 4.2服务器端模板
- 5、传输图像
- 5.1客户端模板
- 5.2服务器端模板
1、读取服务器端文件
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import javax.swing.*;
public class ReadFile{
public static void main (String args []) {
new NetWin() ;
}
}
class NetWin extends JFrame implements ActionListener,Runnable {
JButton button;
URL url;
JTextField inputURLText; //输入 URL
JTextArea area;
byte b[]=new byte[118];
Thread thread;
NetWin(){
inputURLText=new JTextField(20) ;
area=new JTextArea (12,12) ;
button=new JButton("确定") ;
button. addActionListener (this) ;
thread=new Thread (this) ;
JPanel p=new JPanel () ;
p. add (new JLabel ("输入网址:"));
p. add (inputURLText) ;
p. add (button) ;
add (area, BorderLayout . CENTER) ;
add (p, BorderLayout . NORTH) ;
setBounds (60, 60, 560,300) ;
setVisible(true) ;
validate() ;
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed (ActionEvent e) {
if(!(thread.isAlive()))
thread=new Thread(this);
try{ thread.start();
}
catch (Exception ee){
inputURLText.setText("我正在读取"+url);
}
}
public void run() {
try { int n=-1;
area. setText (null) ;
String name=inputURLText.getText() .trim() ;
url=new URL(name);//使用字符串 name创建URL对象
String hostName = url.getHost();//URL调用getHost ()
int urlPortNumber= url.getPort();
String fileName=url.getFile();
InputStream in =url.openStream();//URL 调用方法返回一个输入流
area.append("n主机: "+hostName+"端口:"+urlPortNumber+"包含的文件名字:"+fileName);
area. append("n文件的内容如下:");
while( (n=in.read(b)) !=-1){
String s=new String(b,0,n);
area.append(s);
}
}
catch (MalformedURLException e1) {
inputURLText . setText (""+e1) ;
return;
}
catch (IOException e1) {
inputURLText.setText (""+e1);
return;
}
}
}
2、会结帐的服务器
2.1客户端模板
import java.io.*;
import java.net.*;
import java.util.*;
public class ClientItem{
public static void main(String args[]) {
Scanner scanner=new Scanner (System.in);
Socket clientSocket=null;
DataInputStream inData=null;
DataOutputStream outData=null;
Thread thread;
Read read=null;
try{ clientSocket=new Socket();
read = new Read();
thread = new Thread(read);//负责读取信息的线程
System.out.print("输入服务器的IP:");
String IP = scanner.nextLine();
System.out.print("输入端口号:");
int port = scanner.nextInt();
String enter=scanner.nextLine(); //消耗回车
if (clientSocket. isConnected()) { }
else{
InetAddress address=InetAddress .getByName(IP);
InetSocketAddress socketAddress=new InetSocketAddress(address,port);
clientSocket.connect(socketAddress);
InputStream in=clientSocket.getInputStream();//clientSocket调用getInputStream()返回输入流
OutputStream out=clientSocket.getOutputStream(); //clientSocket调用getOutputStream()返回输出流
inData =new DataInputStream(in);
outData = new DataOutputStream(out);
read.setDataInputStream(inData);
read.setDataOutputStream(outData);
thread.start(); //启动负责读信息的线程
}
}
catch(Exception e) {
System. out.println("服务器已断开"+e);
}
}
}
class Read implements Runnable {
Scanner scanner = new Scanner (System. in) ;
DataInputStream in;
DataOutputStream out;
public void setDataInputStream (DataInputStream in) {
this.in =in;
}
public void setDataOutputStream (DataOutputStream out){
this.out = out;
}
public void run() {
System.out.println("输入账单:") ;
String content = scanner.nextLine() ;
try{ out.writeUTF("账单"+content);
String str = in.readUTF();
System.out.println(str);
str=in.readUTF();
System.out.println(str);
str=in.readUTF();
System.out.println(str);
}
catch (Exception e) {}
}
}
2.2服务器端模板
import java.io.*;
import java.net.*;
import java.util.*;
public class ServerItem {
public static void main (String args[]) {
ServerSocket server=null;
ServerThread thread;
Socket you=null;
while (true) {
try{ server= new ServerSocket(4331);
}//创建在端口4331上负责监听的ServerSocket 对象
catch (IOException e1) {
System. out.println("正在监听");
}
try{ System. out.println("正在等待客户");
you= server.accept(); //server 调用accept ()返回和客户端相连接的Socket对象
System.out.println("客户的地址:"+you.getInetAddress());
}
catch (IOException e) {
System.out.println(""+e);
}
if (you!=null){
new ServerThread(you) .start() ;
}
}
}
}
class ServerThread extends Thread {
Socket socket;
DataInputStream in=null;
DataOutputStream out=null;
ServerThread (Socket t) {
socket=t;
try { out=new DataOutputStream(socket.getOutputStream()) ;
in=new DataInputStream (socket. getInputStream()) ;
}
catch (IOException e) { }
}
public void run() {
try{
String item = in. readUTF () ;
Scanner scanner=new Scanner(item);
scanner.useDelimiter ("[^0123456789.]+");
if(item.startsWith("账单")){
double sum=0;
while (scanner .hasNext()) {
try{
double price = scanner.nextDouble();
sum = sum+price;
System.out.println(price);
}
catch (InputMismatchException exp){
String t=scanner.next();
}
}
out.writeUTF("您的账单:");
out.writeUTF(item);
out.writeUTF("总额:"+sum+"元");
}
}
catch (Exception exp) { }
}
}
3、读取服务器端的窗口
3.1客户端模板
import java.io.*;
import java.net.*;
import java.util.*;
public class Client{
public static void main (String args[]) {
Scanner scanner = new Scanner(System.in);
Socket mysocket=null;
ObjectInputStream inObject=null;
ObjectOutputStream outObject=null;
Thread thread;
ReadWindow readWindow=null;
try{ mysocket=new Socket();
readWindow = new ReadWindow();
thread = new Thread(readWindow);//负责读取信息的线程
System.out.print("输入服务器的IP:");
String IP=scanner.nextLine();
System.out.print("输入端口号:");
int port=scanner.nextInt();
if(mysocket.isConnected()){}
else {
InetAddress address=InetAddress.getByName(IP);
InetSocketAddress socketAddress=new InetSocketAddress(address,port);
mysocket.connect(socketAddress);
InputStream in= mysocket.getInputStream();//mysocket调用getInputStream()返回输入流
OutputStream out=mysocket.getOutputStream();//mysocket调用getOutputStream()返回输出流
inObject =new ObjectInputStream(in) ;
outObject = new ObjectOutputStream(out);
readWindow.setobjectInputStream(inObject);
thread.start();//启动负责读取窗口的线程
}
}
catch (Exception e) {
System.out.println("服务器已断开"+e);
}
}
}
class ReadWindow implements Runnable {
ObjectInputStream in;
public void setobjectInputStream (ObjectInputStream in){
this.in=in;
}
public void run() {
double result=0;
while (true) {
try{ javax.swing.JFrame window = (javax.swing.JFrame) in.readObject();
window.setTitle("这是从服务器.上读入的窗口");
window.setVisible(true) ;
window.requestFocusInWindow() ; // requestFocus() ;
window.setSize(600,800);
}
catch(Exception e){
System.out.println("与服务器已断开"+e);
break;
}
}
}
}
3.2服务器端模板
import java.io.*;
import java.net.*;
import java.util.*;
import java.awt.*;
import javax. swing.*;
public class Server {
public static void main(String args[]) {
ServerSocket server=null;
ServerThread thread;
Socket you=null;
while(true){
try{server=new ServerSocket(4331);//创建在端口4331上负责监听的ServerSocket 对象
}
catch(IOException e1) {
System.out.println("正在监听");
}
try{ you=server.accept();//server 调用accept ()返回和客户端相连接的Socket对象
System.out.println("客户的地址:"+you.getInetAddress());
}
catch(IOException e){
System.out.println("正在等待客户");
}
if (you!=null) {
new ServerThread(you).start();
}
}
}
}
class ServerThread extends Thread {
Socket socket;
ObjectInputStream in=null;
ObjectOutputStream out=null;
JFrame window;
JTextArea text;
ServerThread (Socket t) {
socket=t;
try { out=new ObjectOutputStream (socket.getOutputStream()) ;
in=new ObjectInputStream (socket.getInputStream());
}
catch (IOException e) {}
window =new JFrame();
text=new JTextArea();
for(int i=1;i<=20;i++) {
text.append("你好,我是服务器上的文本区组件n");
}
text.setBackground(Color.yellow);
window.add(text);
window. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void run(){
try{ out.writeObject(window);
}
catch (IOException e) {
System.out.println("客户离开");
}
}
}
4、与服务器玩猜字游戏
4.1客户端模板
public class ClientGuess {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
Socket mysocket=null;
DataInputStream inData=null;
DataOutputStream outData=null;
Thread thread ;
ReadNumber readNumber=null;
try{ mysocket=new Socket();
readNumber = new ReadNumber();
thread=new Thread(readNumber);//负 责读取信息的线程
System.out.print("输入服务器的IP:");
String IP = scanner.nextLine();
System.out.print("输入端口号:");
int port = scanner.nextInt();
if (mysocket. isConnected()) {}
else {
InetAddress address=InetAddress.getByName(IP);
InetSocketAddress socketAddress=new InetSocketAddress(address,port);
mysocket.connect (socketAddress);
InputStream in=mysocket.getInputStream();//mysocket 调用getInputStream()返回输入流
OutputStream out=mysocket.getOutputStream();//mysocket调用getOutputStream()返回输出流
inData=new DataInputStream(in);
outData=new DataOutputStream(out);
readNumber.setDataInputStream(inData);
readNumber.setDataOutputStream(outData);
thread.start(); //启动负 责读取随机数的线程
}
}
catch (Exception e) {
System.out.println("服务器已断开"+e);
}
}
}
class ReadNumber implements Runnable {
Scanner scanner=new Scanner(System.in);
DataInputStream in;
DataOutputStream out;
public void setDataInputStream(DataInputStream in){
this.in = in;
}
public void setDataOutputStream (DataOutputStream out) {
this.out = out;
}
public void run(){
try{
out.writeUTF("Y");
while (true){
String str=in.readUTF() ;
System.out.println(str);
if(!str.startsWith("询问")){
if(str.startsWith("猜对了"))
continue;
System.out.print("好的,我输入猜测:");
int myGuess=scanner.nextInt() ;
String enter=scanner.nextLine(); //消耗多余的Enter符
out.writeInt(myGuess);
}
else{
System.out.print("好的,我输入Y或N:");
String myAnswer = scanner.nextLine();
out.writeUTF(myAnswer);
}
}
}
catch (Exception e) {
System.out.println("与服务器已断开"+e);
return;
}
}
}
4.2服务器端模板
import java.io.*;
import java.net.*;
import java.util.*;
public class ServerNumber {
public static void main(String args[]) {
ServerSocket server=null;
ServerThread thread;
Socket you=null;
while(true){
try{ server=new ServerSocket(4331);//创建在端口4331 上负责监听的ServerSocket 对象
}
catch (IOException el) {
System. out.println("正在监听");
}
try{ you= server.accept();//server 调用accept()返回和客户端相连接的Socket对象
System.out.println("客户的地址:"+you. getInetAddress());
}
catch (IOException e) {
System. out.println("正在等待客户");
}
if (you!=null) {
new ServerThread(you).start();
}
}
}
}
class ServerThread extends Thread {
Socket socket;
DataInputStream in=null;
DataOutputStream out=null;
ServerThread (Socket t) {
socket=t;
try {
out=new DataOutputStream (socket . getOutputStream());
in=new DataInputStream (socket. getInputStream());
}
catch (IOException e) {}
}
public void run(){
try{
while(true){
String str=in.readUTF();
boolean boo =str.startsWith("Y")||str.startsWith("y");
if (boo){
out.writeUTF("给你一个1~ 100的随机数,请猜它是多少呀!");
Random random=new Random();
int realNumber=random.nextInt(100)+1;
handleClientGuess(realNumber);
out.writeUTF("询问:想继续玩输入Y,否则输入N:");
}
else {
return;
}
}
}
catch (Exception exp) {}
}
public void handleClientGuess(int realNumber){
while(true){
try{int clientGuess=in.readInt();
System.out.println(clientGuess);
if(clientGuess>realNumber)
out.writeUTF ("猜大了") ;
else if(clientGuess<realNumber)
out.writeUTF("猜小了");
else if (clientGuess==realNumber){
out.writeUTF("猜对了! ");
break;
}
}
catch (IOException e) {
System.out.println("客户离开");
return;
}
}
}
}
5、传输图像
5.1客户端模板
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
class ImageCanvas extends Canvas{
Image image=null;
public ImageCanvas(){
setSize(200,200);
}
public void paint (Graphics g){
if (image!=null)
g.drawImage(image,0,0,this);
}
public void setImage(Image image){
this.image=image;
}
}
public class ClientGetImage extends JFrame implements Runnable, ActionListener {
JButton b=new JButton("获取图像");
ImageCanvas canvas;
ClientGetImage(){
super("I am a client!");
setSize(320,200);
setVisible(true);
b.addActionListener(this);
add(b,BorderLayout.NORTH);
canvas=new ImageCanvas() ;
add(canvas,BorderLayout.CENTER);
Thread thread=new Thread(this);
validate();
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
thread.start();
}
public void actionPerformed (ActionEvent event){
byte b[]="请发图像".trim().getBytes();
try{ InetAddress address=InetAddress.getByName("127.0.0.1");
DatagramPacket data= new DatagramPacket(b,b.length,address,1234);
//创建 data,该数据包的目标地址和端口分别
//是address和1234,其中的数据为数组b
//的全部字节
DatagramSocket mailsend=new DatagramSocket(); //创建负责发送数据的mailSend对象
mailsend.send(data);//mailSend 发送数据data
}
catch (Exception e) {}
}
public void run(){
DatagramPacket pack=null;
DatagramSocket mailReceive=null;
byte b[]=new byte[8192];
ByteArrayOutputStream out=new ByteArrayOutputStream() ;
try{
pack=new DatagramPacket (b,b. length) ;
mailReceive=new DatagramSocket(5678);//创建在端口5678负责收取数据包的mai1Receive对象
}
catch (Exception e) {}
try{
while (true){
mailReceive.receive(pack);
String message=new String (pack.getData(),0,pack.getLength());
if(message.startsWith("end")){
break;
}
out.write(pack.getData(),0,pack.getLength());
}
byte imagebyte []=out.toByteArray();
out.close();
Toolkit tool=getToolkit();
Image image=tool.createImage(imagebyte);
canvas.setImage(image);
canvas.repaint();
validate();
}
catch (IOException e){}
}
public static void main(String args[]) {
new ClientGetImage();
}
}
5.2服务器端模板
import java.net.*;
import java.io.*;
public class ServerImage{
public static void main(String args[]) {
DatagramPacket pack=null;
DatagramSocket mailReceive=null;
ServerThread thread;
byte b[]=new byte[8192] ;
InetAddress address=null;
pack=new DatagramPacket (b,b.length);
while(true){
try{ mailReceive=new DatagramSocket(1234);
}
catch (IOException e1){
System.out.println("正在等待");
}
try{ mailReceive.receive(pack);
address=pack.getAddress();
System.out.println("客户的地址:"+address);
}
catch(IOException e) {}
if(address!=null) {
new ServerThread (address).start();
}
}
}
}
class ServerThread extends Thread{
InetAddress address;
DataOutputStream out=null;
DataInputStream in=null;
String s=null;
ServerThread (InetAddress address) {
this.address=address;
}
public void run() {
FileInputStream in;
byte b[]=new byte[8192];
try{ in=new FileInputStream("a.jpg");
int n=-1;
while( (n=in. read(b)) !=-1) {
DatagramPacket data=new DatagramPacket (b,n, address,5678);
DatagramSocket mailSend=new DatagramSocket();
mailSend.send(data);
}
in.close();
byte end[]="end" .getBytes() ;
DatagramPacket data=new DatagramPacket(end,end.length,address,5678);
DatagramSocket mailSend=new DatagramSocket();
mailSend.send(data);
}
catch (Exception e) { }
}
}
最后
以上就是烂漫手机为你收集整理的Java上机实验 Java中的网络编程1、读取服务器端文件2、会结帐的服务器3、读取服务器端的窗口4、与服务器玩猜字游戏5、传输图像的全部内容,希望文章能够帮你解决Java上机实验 Java中的网络编程1、读取服务器端文件2、会结帐的服务器3、读取服务器端的窗口4、与服务器玩猜字游戏5、传输图像所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复