导航:首页 > 编程语言 > java网络编程典型代码

java网络编程典型代码

发布时间:2024-04-12 17:20:54

㈠ 求java nio网络编程的小例子,要求客户端一直与服务器保持连接

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

public class chatClient extends Frame {

/**
* @param args
*/
TextField tfTxT=new TextField();
TextArea taContent=new TextArea();
Socket s=null;
DataOutputStream dos=null;
DataInputStream dis=null;
private boolean bConnected =false;

public static void main(String[] args) {
new chatClient().lunachFrame();
}

private class RecvThread implements Runnable{

public void run() {
try{
while(bConnected){
String str=dis.readUTF();
taContent.setText(taContent.getText()+str+'\n');
}
}catch(IOException e){
e.printStackTrace();
}
}

}

public void lunachFrame(){
this.setLocation(400, 300);
this.setSize(300,300);
//this.setLayout(new FlowLayout());
this.add(tfTxT,"South");
this.add(taContent,"North");
pack();
tfTxT.addActionListener(new TFListener());
this.addWindowListener(new WindowClose());
this.setVisible(true);
connect();
new Thread(new RecvThread()).start();
}

public void connect(){
try {
s= new Socket("127.0.0.1",8888);
dos =new DataOutputStream(s.getOutputStream());
dis =new DataInputStream(s.getInputStream());
System.out.println("connected!");
bConnected=true;
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

public void disconnect(){
try {
dos.close();
s.close();
} catch (Exception e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
}

class WindowClose extends WindowAdapter{

@Override
public void windowClosing(WindowEvent e) {
// TODO 自动生成方法存根
System.exit(0);
disconnect();
}

}

private class TFListener implements ActionListener{

public void actionPerformed(ActionEvent e) {
String str=tfTxT.getText().trim();//trim去掉两边空格
//taContent.setText(str);
tfTxT.setText("");
try {
dos.writeUTF(str);
dos.flush();
//dos.close();

} catch (IOException e1) {
e1.printStackTrace();

}
}
}
}

======================================
import java.io.IOException;
import java.net.*;
import java.io.*;
import java.util.*;

public class ChatServer {
List<Client> clients=new ArrayList<Client>();
Client c=null;

public static void main(String[] args){
new ChatServer().start();
}

public void start(){
boolean started=false;
ServerSocket ss=null;
DataInputStream dis=null;
try{
ss=new ServerSocket(8888);
started =true;
}catch(Exception e)
{
e.printStackTrace();
}
try{
while(started){
Socket s=ss.accept();
c=new Client(s);//启动线程,实行run()方法
System.out.println("a client connected!");
new Thread(c).start();//启动start方法,循环.start是Thread中的方法与这上面的start无关
clients.add(c);
//dis.close();
}
} catch (Exception e) {

//e.printStackTrace();
}
finally{
try {
ss.close();
} catch (IOException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
}
}

class Client implements Runnable{

private Socket s;
private DataInputStream dis =null;
private boolean bConnected =false;
private DataOutputStream dos=null;

public Client(Socket s){
this.s=s;
try {
dis=new DataInputStream(s.getInputStream());
dos =new DataOutputStream(s.getOutputStream());
bConnected =true;
} catch (IOException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
}

public void send(String str)throws Exception{
dos.writeUTF(str);

}

public void run() {
try{
while(bConnected){
String str = dis.readUTF();
System.out.println(str);
for(int i=0;i<clients.size();i++){
c=clients.get(i);
c.send(str);
}
/*for(Iterator<Client> it=clients.iterator();it.hasNext();){
Client c=it.next();
c.send(str);
}*/
}
}catch(SocketException e){
clients.remove(this);
System.out.println("客户下线了");
}
catch(EOFException e){
System.out.println("Client closed");
}
catch (Exception e){

//e.printStackTrace();
}
finally{
try {
if(dis !=null) dis.close();
if(dos !=null) dos.close();
if(s!=null) s.close();
} catch (Exception e1) {
// TODO 自动生成 catch 块
//e1.printStackTrace();
}
}
}
}

}

第一个是客户端,
第二个是server端

㈡ Java 网络编程

import java.io.*;
import java.net.*;

public class Sendserver
{
public static int port = 3333;
public static void main(String[] args) throws IOException
{
ServerSocket s = new ServerSocket(port);
Socket d= s.accept();
System.out.println("客户端连接成功");

DataInputStream input = new DataInputStream(d.getInputStream());
int bufferSize = 8192;
byte[] buf = new byte[bufferSize];
DataOutputStream fileOut = new DataOutputStream(new BufferedOutputStream(
new BufferedOutputStream(new FileOutputStream(
"2.mp3"))));
while (true)
{
int read = 0;
if (input != null)
read = input.read(buf);

if (read == -1)
break;

byte[] temp=new byte[read];
for(int i=0;i<read;i++)
temp[i]=buf[i];
fileOut.write(temp);
}
fileOut.close();
System.out.println("传送完毕");

}
}

import java.io.*;
import java.net.*;

public class SendClient
{

public static void main(String[] args) throws UnknownHostException, IOException
{
try{
DataInputStream iinput = new DataInputStream(new BufferedInputStream(
new FileInputStream("1.mp3")));

InetAddress addr = InetAddress.getByName("localhost");
Socket f= new Socket(addr,3333);
OutputStream output=f.getOutputStream();

int bufferSize = 8192;
byte[] buf = new byte[bufferSize];
while (true)
{
int read = 0;
if (iinput != null)
read = iinput.read(buf);

if (read == -1)
break;

byte[] temp=new byte[read];
for(int i=0;i<read;i++)
temp[i]=buf[i];
output.write(temp);
output.flush();
}

iinput.close();
output.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

改动相当大,你自己看看吧。

㈢ 我要一份用java网络编程写的点对点的两人聊天程序(TCP和UDP)

Server端:
import java.io.*;
import java.net.*;
import java.applet.Applet;
public class TalkServer{
public static void main(String args[]) {
try{
ServerSocket server=null;
try{
server=new ServerSocket(4700);
}catch(Exception e) {
System.out.println("can not listen to:"+e);
}
Socket socket=null;
try{
socket=server.accept();
}catch(Exception e) {
System.out.println("Error."+e);
}
String line;
BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter os=new PrintWriter(socket.getOutputStream());
BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Client:"+is.readLine());
line=sin.readLine();
while(!line.equals("bye")){
os.println(line);
os.flush();
System.out.println("Server:"+line);
System.out.println("Client:"+is.readLine());
line=sin.readLine();
}
os.close();
is.close();
socket.close();
server.close();
}catch(Exception e){
System.out.println("Error:"+e);
}
}
}

Client端:
import java.io.*;
import java.net.*;
public class TalkClient {
public static void main(String args[]) {
try{
Socket socket=new Socket("127.0.0.1",4700);
BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));
PrintWriter os=new PrintWriter(socket.getOutputStream());
BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream()));
String readline;
readline=sin.readLine(); //从系统标准输入读入一字符串
while(!readline.equals("bye")){
os.println(readline);
os.flush();
System.out.println("Client:"+readline);
System.out.println("Server:"+is.readLine());
readline=sin.readLine(); //从系统标准输入读入一字符串
}
os.close(); //关闭Socket输出流
is.close(); //关闭Socket输入流
socket.close(); //关闭Socket
}catch(Exception e) {
System.out.println("Error"+e); //出错,则打印出错信息
}
}
}

㈣ Java100行以上源代码,至少五个class以及一个interface,可以简单点

下面是一个可能的Java源代码,它包含了一个接口租冲薯(Shape)和五个类(Circle, Rectangle, Triangle, Square 和 Main)。它的功能是计算不同形状的面积和周长。
//定义一个接口Shape,有两判指个抽象方法:getArea()和getPerimeter()interface Shape { double getArea(); double getPerimeter();
}//定义一个类Circle,实现Shape接口class Circle implements Shape { //定义一个私有属性radius,表示圆的半径
private double radius; //定义一个公有构造方法,用于初始化radius
public Circle(double radius) { this.radius = radius;
} //实现getArea()方法,返回圆的面积
public double getArea() { return Math.PI * radius * radius;
} //实现getPerimeter()方法,返回圆的周长
public double getPerimeter() { return Math.PI * radius * 2;
}
}//定义一个类Rectangle,实现Shape接口class Rectangle implements Shape { //定义两个私有属性width和height,表示矩形的宽度和高度
private double width; private double height; //定义一个公有构造方法,用于初始化width和height
public Rectangle(double width, double height) { this.width = width; this.height = height;
} //实现getArea()方法,返回矩形的面积
public double getArea() { return width * height;
} //实现getPerimeter()方法,返回矩形的周长
public double getPerimeter() { return (width + height) *2;
}
}//定义一个类Triangle,实现Shape接口class Triangle implements Shape { //定义三个私有属性a,b,c表示三角形的三条边长
private double a; private double b; private double c; //定义一个公有构造方法,用于初始化a,b,c,并检查是否满足三角形条件(任意两边之和大于第三边)
public Triangle(double a, double b, double c) throws Exception{ if (a + b > c && a + c > b && b + c > a) {
this.a = a; this.b = b;
this.c = c;
} else {
throw new Exception("Invalid triangle");
}
} //实现getArea()方法,返回三角形的面积(使用海伦公式)
public double getArea() { //计算半周长p
double p = (a + b + c) /2; //计算并返回面积s(使用Math.sqrt()函数求平方根)
return Math.sqrt(p * (p - a) * (p - b) * (p - c));
} //实现getPerimeter()方法,返回三角形的周长
public double getPerimeter(){ return a + b + c;
}
}//定义一个类Square,继承Rectangle类,并重写构造方法和toString()方法class Square extends Rectangle { //重写构造方法,在调用父类构造方法时传入相弊者同的参数side作为width和height
public Square(double side){ super(side, side);
} //重写toString()方法,在原来基础上加上"Square:"前缀,并只显示side属性而不显示width和height属性(使用String.format()函数格式化字符串)
@Override
public String toString(){ return String.format("Square: side=%.2f", super.width); /* 或者直接使用super.getPerimeter()/4作为side */
/* return String.format("Square: side=%.2f", super.getPerimeter()/4); */

/* 注意:不能直接访问super.side属性,

㈤ java socket网络编程

//==============Server.java=================//
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
public static void main(String[] args) throws IOException {
ServerSocket s = new ServerSocket(12345);
System.out.println("服务器就绪,请启动客户端.");
Socket so = s.accept();
byte[] buff = new byte[1024];
int read = so.getInputStream().read(buff);
String[] abc=new String(buff,0,read).split("\\D+");
int a = Integer.parseInt(abc[0]);
int b = Integer.parseInt(abc[1]);
int c = Integer.parseInt(abc[2]);
if(!cbt(a,b,c))
so.getOutputStream().write("输入的数据无法组成三角形.".getBytes());
else
so.getOutputStream().write(getArea(a,b,c).getBytes());
so.getOutputStream().flush();
so.close();
s.close();
}

private static String getArea(int a, int b, int c) {
float s = (a+b+c)/2f;
return "面积: "+Math.sqrt(s*(s-a)*(s-b)*(s-c));
}

private static boolean cbt(int a, int b, int c) {
return a>0&&b>0&&c>0&&a+b>c&&b+c>a&&a+c>b;
}
}

//=================Client.java======================//
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException {
System.out.println("输入三角形的三边并用逗号隔开,如: (3,4,5) ");
byte[] buff=new byte[64];
int r = System.in.read(buff);
String ipaddr = "localhost";//根据情况改变,在本机调试就不改了
Socket so = new Socket(ipaddr,12345);
so.getOutputStream().write(new String(buff,0,r).getBytes());
r = so.getInputStream().read(buff);
so.close();
String rs = new String(buff,0,r);
System.out.println(rs);
}

}

//先启动Server,再启动Client

㈥ java Socket网络编程

调用 outt.flush ();

阅读全文

与java网络编程典型代码相关的资料

热点内容
儿童压缩面膜怎么用法 浏览:91
新车压缩机坏了保修吗 浏览:546
艾默生压缩机说明书 浏览:289
超解压手法 浏览:415
如何获取服务器上的文件地址 浏览:679
文件夹题用另存为吗 浏览:639
各种编译类型为自然选择提供了 浏览:914
cnc玻璃精雕机编程 浏览:313
电脑复制中途改文件夹名字 浏览:498
批处理转exe反编译工具 浏览:76
pdf怎么换成图片 浏览:323
换位加密能够按照一定 浏览:390
安卓开发入门pdf 浏览:192
日医pdf 浏览:861
指定文件夹换壁纸 浏览:898
天玥服务器是什么架构 浏览:236
苹果为什么回购安卓手机 浏览:87
27岁程序员发型 浏览:198
图库文件夹是什么意思 浏览:532
空调压缩机隔音 浏览:352