導航:首頁 > 編程語言 > 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網路編程典型代碼相關的資料

熱點內容
手機怎麼建壓縮包 瀏覽:940
大象裡面的文件夾怎麼打開 瀏覽:953
安卓微信為什麼發不了照片 瀏覽:348
補辦綠本解壓違法嗎 瀏覽:604
gccwindows命令 瀏覽:535
日本性電影 瀏覽:331
都市主角推到母親姐姐姨媽的長篇小說 瀏覽:917
免費不用下載網站 瀏覽:893
可以播放的歐美男男電影 瀏覽:949
ldx218舵機用單片機控制 瀏覽:898
河南dns伺服器地址大全 瀏覽:775
中字四級片 瀏覽:769
青島本地伺服器地址 瀏覽:987
白鹿原小說免費閱讀 瀏覽:356
女主姓簡的小說 瀏覽:210
提示命令符框 瀏覽:354
韓劇倫理女同都有哪些 瀏覽:35
高黃男男小說 瀏覽:503
華娛小說多女主的小說 瀏覽:747
收了楊玉環的歷史小說 瀏覽:878