1. java 可以根據tcp/ip來控制硬體嗎
不行的,tcp/ip只是一些網路層的協議和傳輸層的協議而已。
2. TCP/IP協議 怎麼用JAVA發送和接收二進制數據 要具體實例
1.TCP/IP協議要求信息必須在塊(chunk)中發送和接收,而塊的長度必須是8位的倍數,因此,我們可以認為TCP/IP協議中傳輸的信息是位元組序列。如何發送和解析信息需要一定的應用程序協議。
2.信息編碼:
首先是Java里對基本整型的處理,發送時,要注意:1)每種數據類型的位元組個數;2)這些位元組的發送順序是怎樣的?(little-endian還是
big-endian);3)所傳輸的數值是有符號的(signed)還是無符號的(unsigned)。具體編碼時採用位操作(移位和屏蔽)就可以了。
具體在Java里,可以採用DataOutputStream類和ByteArrayOutputStream來實現。恢復時可以採用
DataInputStream類和ByteArrayInputStream類。
其次,字元串和文本,在一組符號與一組整數之間的映射稱為編碼字元集(coded character
set)。發送者與接收者必須在符號與整數的映射方式上達成共識,才能使用文本信息進行通信,最簡單的方法就是定義一個標准字元集。具體編碼時採用
String的getBytes()方法。
最後,位操作。如果設置一個特定的設為1,先設置好掩碼(mask),之後用或操作;要清空特定一位,用與操作。
3.成幀與解析
成幀(framing)技術解決了接收端如何定位消息的首位位置的問題。
如果接收者試圖從套接字中讀取比消息本身更多的位元組,將可能發生以下兩種情況之一:如果信道中沒有其他消息,接收者將阻塞等待,同時無法處理接收
到的消息;如果發送者也在等待接收端的響應消息,則會形成死鎖(dealock);另一方面,如果信道中還有其他消息,則接收者會將後面消息的一部分甚至
全部讀到第一條消息中去,這將產生一些協議錯誤。因此,在使用TCP套接字時,成幀就是一個非常重要的考慮因素。
有兩個技術:
1.基於定界符(Delimiter-based):消息的結束由一個唯一的標記(unique
marker)指出,即發送者在傳輸完數據後顯式添加的一個特殊位元組序列。這個特殊標記不能在傳輸的數據中出現。幸運的是,填充(stuffing)技術
能夠對消息中出現的定界符進行修改,從而使接收者不將其識別為定界符。在接收者掃描定界符時,還能識別出修改過的數據,並在輸出消息中對其進行還原,從而
使其與原始消息一致。
2.顯式長度(Explicit length):在變長欄位或消息前附加一個固定大小的欄位,用來指示該欄位或消息中包含了多少位元組。這種方法要確定消息長度的上限,以確定保存這個長度需要的位元組數。
介面:
Java代碼 import java.io.IOException; import java.io.OutputStream; public interface Framer { void frameMsg(byte [] message,OutputStream out) throws IOException; byte [] nextMsg() throws IOException; }
定界符的方式:
Java代碼 import java.io.ByteArrayOutputStream; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class DelimFramer implements Framer { private InputStream in;//data source; private static final byte DELIMTER=(byte)'\n';//message delimiter public DelimFramer(InputStream in){ this.in=in; } @Override public void frameMsg(byte[] message, OutputStream out) throws IOException { //ensure that the message dose not contain the delimiter for(byte b:message){ if(b==DELIMTER) throw new IOException("Message contains delimiter"); } out.write(message); out.write(DELIMTER); out.flush(); } @Override public byte[] nextMsg() throws IOException { ByteArrayOutputStream messageBuffer=new ByteArrayOutputStream(); int nextByte; while((nextByte=in.read())!=DELIMTER){ if(nextByte==-1){//end of stream? if(messageBuffer.size()==0){ return null; }else{ throw new EOFException("Non-empty message without delimiter"); } } messageBuffer.write(nextByte); } return messageBuffer.toByteArray(); } }
顯式長度方法:
Java代碼 import java.io.DataInputStream; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class LengthFramer implements Framer { public static final int MAXMESSAGELENGTH=65535; public static final int BYTEMASK=0xff; public static final int SHOTMASK=0xffff; public static final int BYTESHIFT=8; private DataInputStream in;// wrapper for data I/O public LengthFramer(InputStream in) throws IOException{ this.in=new DataInputStream(in); } @Override public void frameMsg(byte[] message, OutputStream out) throws IOException { if(message.length>MAXMESSAGELENGTH){ throw new IOException("message too long"); } //write length prefix out.write((message.length>>BYTEMASK)&BYTEMASK); out.write(message.length&BYTEMASK); //write message out.write(message); out.flush(); } @Override public byte[] nextMsg() throws IOException { int length; try{ length=in.readUnsignedShort(); }catch(EOFException e){ //no (or 1 byte) message; return null; } //0<=length<=65535; byte [] msg=new byte[length]; in.readFully(msg);//if exception,it's a framing error; return msg; } }
3. 在Java中實現TCP協議編程中怎麼傳
在Java中實現TCP協議編程
ServerSocket:編寫TCP網路服務程序,首先要用到java.net.ServerSocket類用以創建伺服器Socket
構造方法:
ServerSocket(intport):創建綁定到特定埠的伺服器套接字
ServerSocket(intport,intbacklog):利用指定的backlog(伺服器忙時保持連接請求的等待客戶數量),創建伺服器套接字並將其綁定到指定的本地埠號。
ServerSocket(intport,intbacklog,InetAddressbindAddr):使用指定的埠、偵聽backlog和要綁定到的本地IP地址創建伺服器。
Socket:客戶端要與伺服器建立連接,必須先創建一個Socket對象
常用構造方法
Socket(Stringhost,intport):創建一個流套接字並將其連接到指定主機上的指定埠號。
Socket(InetAddressaddress,intport):創建一個流套接字並將其連接到指定IP地址的指定埠號。
伺服器端程序調用ServerSocket類中的accept()方法等待客戶端的連接請求,一旦accept()接收了客戶端連接請求,該方法返回一個與該客戶端建立了專線連接的Socket對象,不用程序去創建這個Socket對象。建立了連接的兩個Socket是以IO流的方式進行數據交換的,Java提供了Socket類中的getInputStream()返回Socket的輸入流對象,getOutputStream()返回Socket的輸出流對象。
TCP伺服器與TCP客戶端間的數據的接受圖示:
用TCP實現伺服器與客戶端的「聊天」:
實例代碼:
客戶端:
packagecom.hbsi.net;
importjava.net.Socket;
importjava.io.*;
publicclassTcpClient{
publicstaticvoidmain(String[]args)throwsException{
//1.建立tcp客戶端socket,要確定要連接的伺服器ip,port
Sockets=newSocket("192.168.49.87",9009);
//獲取鍵盤錄入
BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in));
//2.通過建立的socket,獲取輸出流對象
//數據輸出給伺服器端
OutputStreamout=s.getOutputStream();
BufferedWriterbwout=newBufferedWriter(newOutputStreamWriter(out));
//獲取伺服器端返回的數據
//讀取伺服器端發過來的信息InputStreamReader()
BufferedReaderbrin=newBufferedReader(newInputStreamReader(
s.getInputStream()));
Stringline=null;
while((line=br.readLine())!=null){
if(line.equals("over"))
break;
bwout.write(line);
bwout.newLine();
bwout.flush();
Stringstr=brin.readLine();
System.out.println("server:"+str);
}
br.close();
s.close();
}
}
伺服器端:
packagecom.hbsi.net;
importjava.io.BufferedReader;
importjava.io.BufferedWriter;
importjava.io.InputStream;
importjava.io.InputStreamReader;
importjava.io.OutputStreamWriter;
importjava.net.ServerSocket;
importjava.net.Socket;
publicclassTcpServer{
publicstaticvoidmain(String[]args)throwsException{
//1.建立伺服器socket
ServerSocketss=newServerSocket(9009);
//2.調用accept()
Sockets=ss.accept();
System.out.println(s.getInetAddress().getHostAddress()
+"...connection");
//讀取客戶的信息的輸入流
InputStreamin=s.getInputStream();
BufferedReaderbrin=newBufferedReader(newInputStreamReader(in));
//向客戶端發送信息輸出流,服務端向客戶端返回信息OutputStreamWriter()
BufferedWriterbrout=newBufferedWriter(newOutputStreamWriter(
s.getOutputStream())); Stringline=null;
while((line=brin.readLine())!=null){
System.out.println("client:"+line);
brout.write(line.toUpperCase());//伺服器端收到信息後,將信息轉為大寫返回給客戶端toUpperCase()
brout.newLine();
brout.flush();
}
s.close();
ss.close();
}
}
4. java如何通過tcp向指定的IP發送指令並獲得返回的包
以下是一個展示java使用tcp通訊的簡單例子,包括伺服器和客戶端代碼:
/**
*TCPServer
*/
import java.io.*;
import java.net.*;
class TCPServer{
public static void main(String[] args)throws IOException{
ServerSocket listen = new ServerSocket(5050);
Socket server = listen.accept();
InputStream in = server.getInputStream();
OutputStream out = server.getOutputStream();
char c = (char)in.read();
System.out.println("收到:" + c);
out.write('s');
out.close();
in.close();
server.close();
listen.close();
}
}
/**
*TCPClient
*/
import java.io.*;
import java.net.*;
class TCPClient{
public static void main(String[] args)throws IOException{
Socket client = new Socket("127.0.0.1" , 5050);
InputStream in = client.getInputStream();
OutputStream out = client.getOutputStream();
out.write('c');
char c = (char)in.read();
System.out.println("收到:" + c);
out.close();
in.close();
client.close();
}
}
5. 用java編寫一個能進行簡單TCP/IP通信的C/S程序
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServer
{
public static void main(String[] args) throws Exception
{
// 創建伺服器端的socket對象
ServerSocket ss = new ServerSocket(5000);
// 監聽連接
Socket socket = ss.accept();
// 直到連接建立好之後代碼才會往下執行
System.out.println("Connected Successfully!");
}
}
import java.net.Socket;
public class TcpClient
{
public static void main(String[] args) throws Exception
{
Socket socket = new Socket("127.0.0.1", 5000);
}
}
6. 如何用JAVA做TCPIP/串口通訊,請詳細告訴資料文檔或者應用
TCP/IP直接用Socket開發即可(性能要求好的就是使用NIO),或者你去看看Apache的Mina類庫,Mina直接支持了TCP/IP和串口。如果要自己開發串口通信比較麻煩,因為Java層面上不支持串口(硬體)操作要通過javaxcom(win32com.dll)來操作。
7. tcp/ip方式的 socket介面,java能調用不
不太明白說的是什麼,Java的話,只要是socket編程的話,是可以調用你的socket介面,如果是Java調用c程序的話,你就要先把c++弄成外置的庫。
希望能幫到你,請採納我的答案。
8. android tcp/ip和JAVA中的一樣嗎
安卓的網路編程就是直接用的java實現的,
你說的看安卓網路編程和java實際上是一樣的,都行。
但是安卓在實現網路與界面與java稍有不同,安卓的網路連接,文件讀寫等耗時操作必須放在子線程所以還是去看安卓網路編程吧。畢竟你做的是安卓。
9. java代碼TCP/IP網路通信伺服器客戶端,實現雙方信息交互。
packagecom.weixin.test;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.OutputStream;
importjava.net.InetAddress;
importjava.net.ServerSocket;
importjava.net.Socket;
importorg.junit.Test;
publicclassScoketTest{
@Test
publicvoidclient()throwsException{
InetAddressi=InetAddress.getByName("127.0.0.1");
Sockets=newSocket(i,9000);
OutputStreamoutputStream=s.getOutputStream();
outputStream.write("服務端你好,我是客戶端哦!".getBytes());
s.shutdownOutput();
InputStreaminputStream=s.getInputStream();
intlength=0;
byte[]bytes=newbyte[1024];
while((length=inputStream.read(bytes))!=-1){
System.err.println(newString(bytes,0,length));
}
inputStream.close();
outputStream.close();
s.close();
}
@Test
publicvoidserver()throwsException{
ServerSocketserverSocket=newServerSocket(9000);
Socketsocket=serverSocket.accept();
InputStreaminputStream=socket.getInputStream();
OutputStreamoutputStream=socket.getOutputStream();
intlength=0;
byte[]bytes=newbyte[1024];
while((length=inputStream.read(bytes))!=-1){
System.err.println(newString(bytes,0,length));
}
outputStream.write("客戶端你好,本王已收到!".getBytes());
outputStream.close();
inputStream.close();
socket.close();
serverSocket.close();
}
}
10. Java怎麼實現對IP/TCP協議數據包的攔截
眾所周知,JAVA語言雖然在TCP/UDP傳輸方面給予了良好的定義,但對於網路層以下的控制,卻是無能為力的。JPCAP擴展包彌補了這一點。
JPCAP實際上並非一個真正去實現對數據鏈路層的控制,而是一個中間件,JPCAP調用wincap/libpcap,而給JAVA語言提供一個公共的介面,從而實現了平台無關性。在官方網站上聲明,JPCAP支持FreeBSD 3.x, Linux RedHat 6.1, Fedora Core 4, Solaris, and Microsoft Windows 2000/XP等系統。
二.JPCAP機制
JPCAP的整個結構大體上跟wincap/libpcap是很相像的,例如NetworkInterface類對應wincap的typedef struct _ADAPTERADAPTER,getDeviceList()對應pcap_findalldevs()等等。 JPCAP有16個類,下面就其中最重要的4個類做說明。
1.NetworkInterface
該類的每一個實例代表一個網路設備,一般就是網卡。這個類只有一些數據成員,除了繼承自java.lang.Object的基本方法以外,沒有定義其它方法。