java - 在java中使用ipv6进行客户端/服务器套接字编程
问题描述
我正在尝试通过 wifi direct 连接两个设备,然后通过套接字在它们之间传输数据。
在服务端我有这个代码
ArrayList<SendReceive> threadList = new ArrayList<>();
public class ServerClass extends Thread{
ServerSocket server;
{
try {
server = new ServerSocket(8888, 5);
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while (true) {
try {
Socket client =server.accept();
runOnUiThread(new Runnable() {
@Override
public void run() {
appendStatus("Connection from " + client.getRemoteSocketAddress());
}
});
SendReceive serverThread=new SendReceive(client);
threadList.add(serverThread);
serverThread.start();
} catch (Exception e) {
System.out.println("Error occured in main: " + e.getStackTrace());
}
}
}
}
在客户端我有这个代码
public class ClientClass extends Thread{
Socket socket;
String hostAdd;
public ClientClass(InetAddress hostAddress){
hostAdd=hostAddress.getHostAddress();
socket=new Socket();
}
@Override
public void run() {
try {
socket.connect(new InetSocketAddress(hostAdd,8888),500);
runOnUiThread(new Runnable() {
@Override
public void run() {
CONSt.setText("now the client connected to server.");
}
});
sendReceive=new SendReceive(socket);
sendReceive.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
注意:SendReceive 的代码是
private class SendReceive extends Thread{
private Socket socket;
private InputStream inputStream;
private OutputStream outputStream;
public SendReceive(Socket skt){
socket=skt;
try {
inputStream=socket.getInputStream();
outputStream=socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
byte[] buffer =new byte[1024];
int bytes;
while (socket!=null){
try {
bytes=inputStream.read(buffer);
if(bytes>0){
String tempMsg=new String(buffer,0,bytes);
runOnUiThread(new Runnable() {
@Override
public void run() {
appendStatus(tempMsg);
}
});
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void write(byte[] bytes){
try {
outputStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
这项工作与 ipv4 地址类似
ClientClass clientClass= new ClientClass( InetAddress.getByName("192.168.49.1"));
clientClass.start();
但不适用于 ipv6 地址
ClientClass clientClass= new ClientClass( InetAddress.getByName("fe80::58a2:b5ff:fe7f:ea51%p2p0"));
clientClass.start();
我需要使用 ipv6 ,有什么问题!!为什么这段代码不能与 ipv6 和 ipv4 一起工作,我如何使它与 ipv6 一起工作。
我将不胜感激任何答案
解决方案
推荐阅读
- python - 为什么我的键绑定导致我的输入被双击?
- java - 我最近遇到了这个代码片段。此代码打印 Hello 作为输出。我不知道为什么?
- java - 如何使用 Java 向指纹设备发送和接收数据
- django - django中基于模型的缓存而不是基于视图的缓存
- sql - 使用 NOT IN 的 SQL 连接显示不正确的数据
- java - 当我获得 RecyclerView 时,Android 片段会抛出 NPE
- swift - 在 UITableView 中使用 insertRow 的 Swift 无效更新
- javascript - 如何在输入中更改多个元素的位置
- c# - 如何从序列号列中删除水晶报表中的小数点
- python - 将动态表单中的数据存储在数组字段中(postgrsql)