Posix本地通信用于同一设备或native和framework层之间
?? 新建本地Socket:socket
?? 同樣socket函數能夠被用來創建一個本地的socket。子通過指導者函數來創建這socket在這PF_LOCAL協議族。為了使它對于你試驗所用類型的連接,代替修改原因的native幫助函數,一個新的native函數將被定義來創建這局部的sockets。
?? int localSocket=socket(PF_LOCAL,SOCK_STREAM,0);
?? 這本地的socket端口地址僅僅只要一個名字組成。它并沒有一個IP地址或者一個端口號。本地的socket名字通過以下兩種命名空間來創建:
???? Abstract 命名空間在本地socket通信端口模塊被維護。這socket名字以一個NULL字符為前綴用于綁定著socket名字。
??? Filesystem命名空間通過這文件系統作為一個特別的socket文件被維護。這socket名字被直接傳遞到了這sockaddr_un結構體來綁定著socket名字到這socket。
? struct sockaddr_un address;
// Name length
const size_t nameLength = strlen(name);
// Path length is initiall equal to name length
size_t pathLength = nameLength;
// If name is not starting with a slash it is
// in the abstract namespace
bool abstractNamespace = ('/' != name[0]);
// Abstract namespace requires having the first
// byte of the path to be the zero byte, update
// the path length to include the zero byte
if (abstractNamespace)
{
pathLength++;
}
// Check the path length
if (pathLength > sizeof(address.sun_path))
{
// Throw an exception with error number
ThrowException(env, "java/io/IOException", "Name is too big.");
}
else
{
// Clear the address bytes
memset(&address, 0, sizeof(address));
address.sun_family = PF_LOCAL;
// Socket path
char* sunPath = address.sun_path;
// First byte must be zero to use the abstract namespace
if (abstractNamespace)
{
*sunPath++ = NULL;
}
// Append the local name
strcpy(sunPath, name);
// Address length
socklen_t addressLength =
Download at http://www.pin5i.com/
268 CHAPTER 10: POSIX Socket API: Local Communication
(offsetof(struct sockaddr_un, sun_path))
+ pathLength;
// Unlink if the socket name is already binded
unlink(address.sun_path);
// Bind socket
LogMessage(env, obj, "Binding to local name %s%s.",
(abstractNamespace) ? "(null)" : "",
name);
if (?1 == bind(sd, (struct sockaddr*) &address, addressLength))
{
// Throw an exception with error number
ThrowErrnoException(env, "java/io/IOException", errno);
}
}
?
Accept在本地Socket:accept
? 這同樣的accept函數被使用來接收到來的連接到這本地的sockt,這位于的不用和客戶端端口地址是accept返回江蘇soketaddr_un類型的。
??
?
總結
以上是生活随笔為你收集整理的Posix本地通信用于同一设备或native和framework层之间的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Socket UDP无连接通信
- 下一篇: NDK 原生代码处理图形