本文目錄一覽:
- 1、java代碼TCP/IP網絡通信服務器客戶端,實現雙方信息交互。
- 2、用java編寫一個能進行簡單TCP/IP通信的C/S程序
- 3、java如何通過tcp發送指令
- 4、在Java中實現TCP協議編程中怎麼傳
- 5、TCP/IP協議 怎麼用JAVA發送和接收二進制數據 要具體實例
java代碼TCP/IP網絡通信服務器客戶端,實現雙方信息交互。
package com.weixin.test;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import org.junit.Test;
public class ScoketTest {
@Test
public void client() throws Exception{
InetAddress i=InetAddress.getByName(“127.0.0.1”);
Socket s=new Socket(i, 9000);
OutputStream outputStream = s.getOutputStream();
outputStream.write(“服務端你好,我是客戶端哦!”.getBytes());
s.shutdownOutput();
InputStream inputStream=s.getInputStream();
int length=0;
byte[] bytes=new byte[1024];
while ((length=inputStream.read(bytes))!=-1) {
System.err.println(new String(bytes,0,length));
}
inputStream.close();
outputStream.close();
s.close();
}
@Test
public void server() throws Exception{
ServerSocket serverSocket=new ServerSocket(9000);
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
int length=0;
byte[] bytes=new byte[1024];
while ((length=inputStream.read(bytes))!=-1) {
System.err.println(new String(bytes, 0,length));
}
outputStream.write(“客戶端你好,本王已收到!”.getBytes());
outputStream.close();
inputStream.close();
socket.close();
serverSocket.close();
}
}
用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);
}
}
java如何通過tcp發送指令
以下是一個展示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();
}
}
在Java中實現TCP協議編程中怎麼傳
在Java中實現TCP協議編程
ServerSocket:編寫TCP網絡服務程序,首先要用到java.net.ServerSocket類用以創建服務器Socket
構造方法:
ServerSocket(int port):創建綁定到特定端口的服務器套接字
ServerSocket(int port, int backlog):利用指定的backlog(服務器忙時保持連接請求的等待客戶數量),創建服務器套接字並將其綁定到指定的本地端口號。
ServerSocket(int port, int backlog, InetAddress bindAddr):使用指定的端口、偵聽 backlog 和要綁定到的本地 IP 地址創建服務器。
Socket:客戶端要與服務器建立連接,必須先創建一個Socket對象
常用構造方法
Socket(String host, int port):創建一個流套接字並將其連接到指定主機上的指定端口號。
Socket(InetAddress address, int port):創建一個流套接字並將其連接到指定 IP 地址的指定端口號。
服務器端程序調用ServerSocket類中的accept()方法等待客戶端的連接請求,一旦accept()接收了客戶端連接請求,該方法返回一個與該客戶端建立了專線連接的Socket對象,不用程序去創建這個Socket對象。建立了連接的兩個Socket是以IO流的方式進行數據交換的,Java提供了Socket類中的getInputStream()返回Socket的輸入流對象,getOutputStream()返回Socket的輸出流對象。
TCP服務器與TCP客戶端間的數據的接受圖示:
創建一個TCP服務器端程序的步驟
(1)創建一個ServerSocket
(2)從ServerSocket接受客戶連接請求
(3)創建一個服務線程處理新的連接
(4)在服務線程中,從socket中獲得I/O流
(5)對I/O流進行讀寫操作,完成與客戶的交互
(6)關閉I/O流
(7)關閉Socket
ServerSocket server=new ServerSocket(port)
Socket s =server.accept();
ObjectInputStream in=new ObjectInputStream(s.getInputStream());
ObjectOutputStream out=new ObjectOutputStream(s.getOutputStream());
out.close();
in.close();
s.close();
創建一個TCP客戶端程序的步驟
(1)創建Socket
(2)獲得I/O流
(3)對I/O流進行讀寫操作
(4)關閉I/O流
(5)關閉Socket
Socket connection =new Socket(127.0.0.1,9009);
ObjectInputStream input=new ObjectInputStream(connection.getInputStream());
ObjectOutputStream output=new ObjectOutputStream(connection.getOutputStream());
output.close();
input.close();
connection.close();
用TCP實現服務器與客戶端的“聊天”:
實例代碼:
客戶端:
package com.hbsi.net;
import java.net.Socket;
import java.io.*;
public class TcpClient{
public static void main(String[] args) throws Exception {
// 1.建立tcp客戶端socket,要確定要連接的服務器ip,port
Socket s = new Socket(“192.168.49.87”, 9009);
// 獲取鍵盤錄入
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// 2.通過建立的socket,獲取輸出流對象
// 數據輸出給服務器端
OutputStream out = s.getOutputStream();
BufferedWriter bwout = new BufferedWriter(new OutputStreamWriter(out));
// 獲取服務器端返回的數據
// 讀取服務器端發過來的信息InputStreamReader()
BufferedReader brin = new BufferedReader(new InputStreamReader(
s.getInputStream()));
String line = null;
while ((line = br.readLine()) != null) {
if (line.equals(“over”))
break;
bwout.write(line);
bwout.newLine();
bwout.flush();
String str = brin.readLine();
System.out.println(“server:” + str);
}
br.close();
s.close();
}
}
服務器端:
package com.hbsi.net;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServer{
public static void main(String[] args) throws Exception {
// 1.建立服務器socket
ServerSocket ss = new ServerSocket(9009);
// 2.調用accept()
Socket s = ss.accept();
System.out.println(s.getInetAddress().getHostAddress()
+ “…connection”);
// 讀取客戶的信息的輸入流
InputStream in = s.getInputStream();
BufferedReader brin = new BufferedReader(new InputStreamReader(in));
// 向客戶端發送信息輸出流,服務端向客戶端返回信息OutputStreamWriter()
BufferedWriter brout = new BufferedWriter(new OutputStreamWriter(
s.getOutputStream())); String line = null;
while ((line = brin.readLine()) != null) {
System.out.println(“client:” + line);
brout.write(line.toUpperCase());//服務器端收到信息後,將信息轉為大寫返回給客戶端toUpperCase()
brout.newLine();
brout.flush();
}
s.close();
ss.close();
}
}
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.lengthMAXMESSAGELENGTH){ throw new IOException(“message too long”); } //write length prefix out.write((message.lengthBYTEMASK)BYTEMASK); out.write(message.lengthBYTEMASK); //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; } }
原創文章,作者:UGFK,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/140564.html