java程序设计基础教程第二版: cilent_p313

本文介绍了一个使用Java实现的简单客户端-服务器通信程序。该程序通过Socket进行网络通信,客户端可以输入三角形边长并通过网络发送给服务器,接收并显示服务器返回的结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.io.*;
import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.event.*;
import java.net.*;
public class cilent_p313 {
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO 自动生成方法存根
        new ComputerCilent();
    }

}
class ComputerCilent extends Frame implements Runnable,ActionListener{
    Button connection,send;
    TextField inputText,showResult;
    Socket socket=null;
    DataInputStream in=null;
    DataOutputStream out=null;
    Thread thread;
    ComputerCilent(){
        socket=new Socket();
        setLayout(new FlowLayout());
        Box box=Box.createVerticalBox();
        connection=new Button("连接");
        send=new Button("send");
        inputText=new TextField(12);
        showResult=new TextField(12);
        box.add(connection);
        box.add(new Label("输入三角形的长度,逗号分隔"));
        box.add(inputText);
        box.add(new Label("show Result"));
        box.add(send);
        box.add(showResult);
        connection.addActionListener(this);
        send.addActionListener(this);
        thread=new Thread(this);
        add(box);
        setBounds(12,12,444,444);
        setVisible(true);
        validate();
        addWindowListener(new WindowAdapter(){
            public void actionPerformed(WindowEvent we){
                System.exit(0);
               
            }
        });
    }
    public void actionPerformed(ActionEvent ae){
        if(ae.getSource()==connection){
            try{
                if(socket.isConnected()){}
                else{
                    InetAddress address=InetAddress.getByName("127.0.0.1");
                    InetSocketAddress socketAddress=new InetSocketAddress(address,4331);
                    socket.connect(socketAddress);
                    in=new DataInputStream(socket.getInputStream());
                    out=new DataOutputStream(socket.getOutputStream());
                    thread.start();
                   
                }
            }
            catch(IOException IOE){}
        }
        if(ae.getSource()==send){
            String s=inputText.getText();
            if(s!=null){
                try{
                        out.writeUTF(s);
                        }
                catch(IOException IOE2){}
            }
        }
    }
    public void run(){
        String s=null;
        while(true){
            try{s=in.readUTF();
            showResult.setText(s);
            }
            catch(IOException IOE3){
                showResult.setText("Lost Connection");
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值