java以太坊客戶端實現
㈠ 用Java socket 實現客戶端與伺服器之間的數據的發送與接受。。。雙向的
下面是一個簡單的通訊實例,進行Server和Client之間的文件傳輸。。如果是簡單的文本傳輸的話簡化掉文本操作的內容即可。。
1.伺服器端
package sterning;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerTest {
int port = 8821;
void start() {
Socket s = null;
try {
ServerSocket ss = new ServerSocket(port);
while (true) {
// 選擇進行傳輸的文件
String filePath = "D:\\lib.rar";
File fi = new File(filePath);
System.out.println("文件長度:" + (int) fi.length());
// public Socket accept() throws
// IOException偵聽並接受到此套接字的連接。此方法在進行連接之前一直阻塞。
s = ss.accept();
System.out.println("建立socket鏈接");
DataInputStream dis = new DataInputStream(new BufferedInputStream(s.getInputStream()));
dis.readByte();
DataInputStream fis = new DataInputStream(new BufferedInputStream(new FileInputStream(filePath)));
DataOutputStream ps = new DataOutputStream(s.getOutputStream());
//將文件名及長度傳給客戶端。這里要真正適用所有平台,例如中文名的處理,還需要加工,具體可以參見Think In Java 4th里有現成的代碼。
ps.writeUTF(fi.getName());
ps.flush();
ps.writeLong((long) fi.length());
ps.flush();
int bufferSize = 8192;
byte[] buf = new byte[bufferSize];
while (true) {
int read = 0;
if (fis != null) {
read = fis.read(buf);
}
if (read == -1) {
break;
}
ps.write(buf, 0, read);
}
ps.flush();
// 注意關閉socket鏈接哦,不然客戶端會等待server的數據過來,
// 直到socket超時,導致數據不完整。
fis.close();
s.close();
System.out.println("文件傳輸完成");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String arg[]) {
new ServerTest().start();
}
}
2.socket的Util輔助類
package sterning;
import java.net.*;
import java.io.*;
public class ClientSocket {
private String ip;
private int port;
private Socket socket = null;
DataOutputStream out = null;
DataInputStream getMessageStream = null;
public ClientSocket(String ip, int port) {
this.ip = ip;
this.port = port;
}
/** *//**
* 創建socket連接
*
* @throws Exception
* exception
*/
public void CreateConnection() throws Exception {
try {
socket = new Socket(ip, port);
} catch (Exception e) {
e.printStackTrace();
if (socket != null)
socket.close();
throw e;
} finally {
}
}
public void sendMessage(String sendMessage) throws Exception {
try {
out = new DataOutputStream(socket.getOutputStream());
if (sendMessage.equals("Windows")) {
out.writeByte(0x1);
out.flush();
return;
}
if (sendMessage.equals("Unix")) {
out.writeByte(0x2);
out.flush();
return;
}
if (sendMessage.equals("Linux")) {
out.writeByte(0x3);
out.flush();
} else {
out.writeUTF(sendMessage);
out.flush();
}
} catch (Exception e) {
e.printStackTrace();
if (out != null)
out.close();
throw e;
} finally {
}
}
public DataInputStream getMessageStream() throws Exception {
try {
getMessageStream = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
return getMessageStream;
} catch (Exception e) {
e.printStackTrace();
if (getMessageStream != null)
getMessageStream.close();
throw e;
} finally {
}
}
public void shutDownConnection() {
try {
if (out != null)
out.close();
if (getMessageStream != null)
getMessageStream.close();
if (socket != null)
socket.close();
} catch (Exception e) {
}
}
}
3.客戶端
package sterning;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
public class ClientTest {
private ClientSocket cs = null;
private String ip = "localhost";// 設置成伺服器IP
private int port = 8821;
private String sendMessage = "Windwos";
public ClientTest() {
try {
if (createConnection()) {
sendMessage();
getMessage();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
private boolean createConnection() {
cs = new ClientSocket(ip, port);
try {
cs.CreateConnection();
System.out.print("連接伺服器成功!" + "\n");
return true;
} catch (Exception e) {
System.out.print("連接伺服器失敗!" + "\n");
return false;
}
}
private void sendMessage() {
if (cs == null)
return;
try {
cs.sendMessage(sendMessage);
} catch (Exception e) {
System.out.print("發送消息失敗!" + "\n");
}
}
private void getMessage() {
if (cs == null)
return;
DataInputStream inputStream = null;
try {
inputStream = cs.getMessageStream();
} catch (Exception e) {
System.out.print("接收消息緩存錯誤\n");
return;
}
try {
//本地保存路徑,文件名會自動從伺服器端繼承而來。
String savePath = "E:\\";
int bufferSize = 8192;
byte[] buf = new byte[bufferSize];
int passedlen = 0;
long len=0;
savePath += inputStream.readUTF();
DataOutputStream fileOut = new DataOutputStream(new BufferedOutputStream(newBufferedOutputStream(new FileOutputStream(savePath))));
len = inputStream.readLong();
System.out.println("文件的長度為:" + len + "\n");
System.out.println("開始接收文件!" + "\n");
while (true) {
int read = 0;
if (inputStream != null) {
read = inputStream.read(buf);
}
passedlen += read;
if (read == -1) {
break;
}
//下面進度條本為圖形界面的prograssBar做的,這里如果是打文件,可能會重復列印出一些相同的百分比
System.out.println("文件接收了" + (passedlen * 100/ len) + "%\n");
fileOut.write(buf, 0, read);
}
System.out.println("接收完成,文件存為" + savePath + "\n");
fileOut.close();
} catch (Exception e) {
System.out.println("接收消息錯誤" + "\n");
return;
}
}
public static void main(String arg[]) {
new ClientTest();
}
}
㈡ 怎麼用java編寫簡單客戶端程序
我這里有一個例子希望能夠幫助你
public class Client{
private Socket socket;
try{
Socket socket=new Socket ("localhoast',8088);
ip=InetAddress.getLocalHost();
String localip=ip.getHostAddress();
System.out.println(localip);
String name=ip.getHostName();
System.out.println(name);
}
catch(Exception e){
}
public void start(){
try{
Run r2=new Run();
Thread t1=new Thread(r2);
t1.setDaemon(true);
t1.start();
Scanner sc=new Scanner(System.in);
OutputStream os=socket.getOutputStream();
OutputStreamWriter osw=new OutputStreamWriter(os);
PrintWriter writer=new PrintWriter(osw,true);
while(true){
writer.println(sc.nextLine());
}
}catch(Exception e){
}
}
public static void main(String args[]){
Client client=new Client();
client.start();
}
class Run implements Runnable{
public void run() {
while(true){
try {
InputStream is=socket.getInputStream();
InputStreamReader isr=new InputStreamReader(is);
BufferedReader br=new BufferedReader(isr);
while(true){
String str=br.readLine();
System.out.println("伺服器說:"+str);
if("bye".equals(str)){
System.out.println("再見客戶端");
System.out.println("聊天結束");
}
}
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
㈢ java 網路編程: 如何實現客戶端與客戶端之間的之間通信
(1)伺服器首先啟動監聽程序,對指定的埠進行監聽,等待接收客戶端的連接請求。
(2)客戶端程序啟動,請求連接伺服器的指定埠。
(3)伺服器收到客戶端的連接請求後與客戶端建立套接字連接。
(4)連接成功後,客戶端與伺服器分別打開兩個流,其中客戶端的輸入流連接到伺服器的輸出流,伺服器的輸入流
連接到客戶端的輸出流,兩邊的流建立連接後就可以雙向的通信了。
(5)當通信完畢後客戶端與伺服器端兩邊各自斷開連接。
㈣ 編寫java程序實現客戶端和服務端的通信
伺服器端:
public class Server{
public static void main(String[] args){
ServerSocket ss = new ServerSocket(埠號);
Socket s = ss.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
String str = br.readLine();
System.out.println(str);
br.close();
s.close();
ss.close();
}
}
客戶端:
public class Client{
public static void main(String[] args){
Socket s = new Socket(ip,埠)
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
bw.write("hello");
bw.flush();
bw.close();
s.close();
}
}
先啟動伺服器端在啟動客戶端,兩個埠要一致,如果是同一台電腦的ip可寫為"127.0.0.1"
㈤ 用Java 的socket實現客戶端的功能
//服務端程序:
importjava.io.*;
importjava.net.*;
publicclassTCPServer{
publicstaticvoidmain(String[]args)throwsIOException{
newTCPServer().init();
}
@SuppressWarnings("static-access")
privatevoidinit()throwsIOException{
@SuppressWarnings("resource")
ServerSocketserver=newServerSocket(1000);
Socketclient=null;
while(true){
try{
client=server.accept();
BufferedInputStreambis=newBufferedInputStream(client.getInputStream());
byte[]b=newbyte[1024];
intlen=0;
Stringmessage="";
while((len=bis.read(b))!=-1){
message=newString(b,0,len);
System.out.print("客戶端:"+client.getInetAddress().getLocalHost().getHostAddress()+"發來消息:"+message);
if("byte".equals(message.trim()))
client.close();
PrintWriterpw=newPrintWriter(client.getOutputStream(),true);
pw.println(message);
}
}catch(Exceptione){
System.err.println("客戶端:"+client.getInetAddress().getLocalHost().getHostAddress()+"已斷開連接!");
}
}
}
}
//客戶端程序:
importjava.io.*;
importjava.net.Socket;
{
publicstaticvoidmain(String[]args)throwsIOException{
newTCPClient().init();
}
privatevoidinit()throwsIOException{
@SuppressWarnings("resource")
finalSocketclient=newSocket("127.0.0.1",1000);
BufferedReaderin=newBufferedReader(newInputStreamReader(System.in));
Stringsend="";
while(true){
send=in.readLine();
PrintWriterout=newPrintWriter(client.getOutputStream(),true);
if(!"byte".equals(send.trim()))
out.println(send);
else{
out.println(send);
System.exit(0);
}
newThread(newTCPClient(){
@SuppressWarnings("static-access")
publicvoidrun(){
try{
BufferedInputStreambis=newBufferedInputStream(client.getInputStream());
byte[]b=newbyte[1024];
intlen=0;
while((len=bis.read(b))!=-1){
System.out.println("伺服器:"+client.getInetAddress().getLocalHost().getHostAddress()+"發來消息:"+newString(b,0,len).trim());
}
}catch(IOExceptione){
System.err.println("連接伺服器失敗!");
}
}
}).start();
}
}
publicvoidrun(){}
}
//伺服器測試結果:
客戶端:192.168.0.200發來消息:001 byte
客戶端:192.168.0.200發來消息:byte
客戶端:192.168.0.200 已斷開連接!
客戶端:192.168.0.200發來消息:adasd
客戶端:192.168.0.200 已斷開連接!
//客戶端測試結果:
---001號客戶端--
001byte
伺服器:192.168.0.200發來消息:001byte
byte //001禮貌說跟伺服器說byte
---002號客戶端--
adasd //002客戶端直接關閉程序
伺服器:192.168.0.200發來消息:adasd
㈥ 用java代碼實現客戶端與服務端建立連接
套接字 Socket
import java.net.*;
Server:
ServerSocket server=new ServerSocket(port);//port是埠
Socket socket=server.accept();
//等待客戶機的連接請求,若連接,則創建一套接字,並將返回。
Client:
Socket socket=new Socket("host",port);//host主機名(本機:127.0.0.1)
㈦ Java 編程 怎麼做成客戶端
打成jar包,寫個bat文件,使用java -jar命令運行
㈧ 用Java編寫創建一對客戶端/伺服器程序,利用數據報將一個文件從一台主機傳送到另一
下面是我自己寫的一個讀取並顯示txt文件的demo,希望對您有幫助。
publicclassClient{
publicstaticvoidmain(String[]args){
ClientFramef=newClientFrame();
}
}
importjava.awt.BorderLayout;
importjava.awt.Container;
importjava.awt.Dimension;
importjava.awt.GridLayout;
importjava.awt.Toolkit;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjava.io.DataInputStream;
importjava.io.DataOutputStream;
importjava.io.IOException;
importjava.net.Socket;
importjava.net.UnknownHostException;
importjava.util.Vector;
importjavax.swing.BorderFactory;
importjavax.swing.JButton;
importjavax.swing.JFrame;
importjavax.swing.JList;
importjavax.swing.JScrollPane;
importjavax.swing.JTextArea;
importjavax.swing.event.ListSelectionEvent;
importjavax.swing.event.ListSelectionListener;
,ListSelectionListener{
privateJListlist=null;
privateJButtonsbtn=null;
privateJButtoncbtn=null;
privateVectorv=null;
privateJTextAreatxt=null;
privateContainercontrol=null;
privateContainerbtn=null;
privateSocketclient=null;
privateDataInputStreamreader=null;
privateDataOutputStreamwriter=null;
publicClientFrame(){
this.list=newJList();
this.list.setBorder(BorderFactory.createTitledBorder("文件列表"));
this.list.addListSelectionListener(this);
this.sbtn=newJButton("顯示");
this.sbtn.addActionListener(this);
this.cbtn=newJButton("清除");
this.cbtn.addActionListener(this);
this.control=newContainer();
this.control.setPreferredSize(newDimension(150,400));
this.control.setLayout(newBorderLayout());
this.control.add(newJScrollPane(this.list),BorderLayout.CENTER);
this.btn=newContainer();
this.btn.setLayout(newGridLayout(1,2));
btn.add(sbtn);
btn.add(cbtn);
this.control.add(this.btn,BorderLayout.SOUTH);
this.txt=newJTextArea();
this.txt.setEditable(false);
this.txt.setSize(350,400);
this.setTitle("客戶端");
this.setSize(500,400);
this.setVisible(true);
DimensiondisplaySize=Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation((displaySize.width-this.getWidth())/2,(displaySize.height-this.getHeight())/2);
this.setLayout(newBorderLayout());
this.add(this.control,BorderLayout.WEST);
this.add(newJScrollPane(this.txt),BorderLayout.CENTER);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try{
//this.client=newSocket("192.168.32.34",6666);
this.client=newSocket("192.168.1.100",6666);
this.reader=newDataInputStream(client.getInputStream());
this.writer=newDataOutputStream(client.getOutputStream());
}catch(UnknownHostExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
}
publicvoidactionPerformed(ActionEventevent){
if(event.getSource()==sbtn){
if(v==null){
v=newVector();
}
else{
v.clear();
}
try{
writer.writeUTF("getfilelist");
writer.flush();
Stringt=reader.readUTF();
while(t!=null&&!t.equals("")){
v.add(t);
t=reader.readUTF();
}
}catch(UnknownHostExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
this.list.setListData(v);
}
if(event.getSource()==cbtn){
this.txt.setText("");
}
}
publicvoidvalueChanged(ListSelectionEvente){
inti=this.list.getSelectedIndex();
if(!this.list.getValueIsAdjusting()&&i!=-1){
try{
writer.writeUTF("getfilecontent_"+i);
writer.flush();
Stringtmp=reader.readUTF();
this.txt.setText(tmp);
}catch(IOExceptione1){
e1.printStackTrace();
}
}
}
}
importjava.io.DataInputStream;
importjava.io.DataOutputStream;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.IOException;
importjava.io.InputStreamReader;
importjava.io.Reader;
importjava.net.ServerSocket;
importjava.net.Socket;
importjava.util.ArrayList;
importjava.util.Iterator;
publicclassServer{
staticArrayList<File>fileArray=newArrayList<File>();
publicstaticvoidmain(Stringargs[]){
ServerSocketserver=null;
Socketclient=null;
Stringcmd="";
try{
server=newServerSocket(6666);
client=server.accept();
DataInputStreamreader=newDataInputStream(client.getInputStream());
DataOutputStreamwriter=newDataOutputStream(client.getOutputStream());
while(true){
cmd=reader.readUTF();
System.out.println(cmd);
if(cmd.equals("getfilelist")){
fileArray.clear();
//fileArray=getFile(newFile("D:/tmp"));
fileArray=getFile(newFile("D:/學習/教程/學習筆記"));
Stringfn="";
for(intk=0;k<fileArray.size();k++){
fn=fileArray.get(k).getName();
writer.writeUTF(fn);
writer.flush();
}
writer.writeUTF("");
}
if(cmd.startsWith("getfilecontent_")){
inti=Integer.parseInt(cmd.split("_")[1]);
Filef=fileArray.get(i);
Readerin=newInputStreamReader(newFileInputStream(f));
inttempbyte;
Stringstr="";
while((tempbyte=in.read())!=-1){
str+=(char)tempbyte;
//System.out.println(str);
}
in.close();
writer.writeUTF(str);
}
}
}catch(IOExceptione){
e.printStackTrace();
}
}
privatestaticArrayList<File>getFile(Filef){
File[]ff=f.listFiles();
for(Filechild:ff){
if(child.isDirectory()){
getFile(child);
}else{
fileArray.add(child);
}
}
returnfileArray;
}
}
㈨ java 編寫網路客戶/伺服器程序,實現如下功能: (1)設計伺服器程序,運行時等待客戶端連接; (2)客戶
Server:
package s;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(10001);
while (true) {
Socket socket = server.accept();
System.out.println("a socket in");
new UpderDeal(socket).start();
}
}
}
class UpderDeal extends Thread {
private Socket s = null;
public UpderDeal(Socket s) {
this.s = s;
}
public void run() {
byte[] b = new byte[1024];
String msg = null;
int len = 0;
try {
while (true) {
len = s.getInputStream().read(b);
msg = new String(b, 0, len);
msg = msg.toUpperCase();
s.getOutputStream().write(msg.getBytes());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client:
package c;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws UnknownHostException,
IOException {
Socket socket = new Socket("localhost", 10001);
OutputStream out = socket.getOutputStream();
InputStream in = socket.getInputStream();
String msg = null;
Scanner sc = new Scanner(System.in);
new Recieve(in).start();
while (true) {
msg = sc.next();
if (msg.equals("exit")) {
break;
}
System.out.println("發出的信息:" + msg);
out.write(msg.getBytes());
}
}
}
class Recieve extends Thread {
private InputStream in = null;
public Recieve(InputStream in) {
this.in = in;
}
public void run() {
byte[] b = new byte[1024];
int len = 0;
while (true) {
try {
len = in.read(b);
System.out.println("收到的信息為:" + new String(b, 0, len));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
希望可以幫到你,還有一種非同步用SocketChannel的,我也怎麼用過,可以網上參考一下。