62,615
社区成员
发帖
与我相关
我的任务
分享
public class client {
public static void main(String[] args) throws IOException {
Socket client = new Socket("localhost",111);
//创建socket连接
InputStream inputStream = client.getInputStream();
OutputStream outputStream = client.getOutputStream();
byte[] integer = new byte[4];
int i = 1;
while(true){
//发送数据 也可以发送字符串String s = 你想说的话;然后:s.getBytes("utf-8")获得byte数组,然后用write方法写
outputStream.write( new byte[] {
(byte) ((i >> 24) & 0xFF),
(byte) ((i >> 16) & 0xFF),
(byte) ((i >> 8) & 0xFF),
(byte) (i & 0xFF)
});
outputStream.flush();
System.out.println("向服务器传输:" + i);
//和服务器一样的
inputStream.read(integer);
i = (integer[0] & 0xff) << 24 |
(integer[1] & 0xff) << 16 |
(integer[2] & 0xff) << 8 |
(integer[3] & 0xff);
i++;
System.out.println("获得服务器数据:" + i);
}
}
}
public class Main {
public static void main(String[] args) throws IOException {
// write your code here
ServerSocket serverSocket = new ServerSocket(111);
while(true){
Socket client = serverSocket.accept();
//创建新线程处理客户端请求
new Thread(()->{
try {
InputStream inputStream = client.getInputStream();
OutputStream outputStream = client.getOutputStream();
//获取输入输出流
byte[] integer = new byte[4];
int i = 0;
while(i<10){
inputStream.read(integer);
//阻塞方式读取数据(如果是对话,那么上面的byte数组的大小可以适当增加,比如加到 2048,视情况而定
//String s = new String(integer,"utf-8"); 这种方式可以获取字符串字节
i = (integer[0] & 0xff) << 24 |
(integer[1] & 0xff) << 16 |
(integer[2] & 0xff) << 8 |
(integer[3] & 0xff);
System.out.println("获得客户端信息:" + i);
i++;
//outputStream.write(s.getBytes("utf-8"));写入输出流
outputStream.write( new byte[] {
(byte) ((i >> 24) & 0xFF),
(byte) ((i >> 16) & 0xFF),
(byte) ((i >> 8) & 0xFF),
(byte) (i & 0xFF)
});
//清空缓冲区
outputStream.flush();
System.out.println("向客户端发送:" + i);
}
}catch(Exception e){
}
}).start();
}
}
}
public class Main {
public static void main(String[] args) throws IOException {
// write your code here
ServerSocket serverSocket = new ServerSocket(111);
while(true){
Socket client = serverSocket.accept();
//创建新线程处理客户端请求
new Thread(()->{
try {
InputStream inputStream = client.getInputStream();
OutputStream outputStream = client.getOutputStream();
//获取输入输出流
byte[] integer = new byte[4];
int i = 0;
while(i<10){
inputStream.read(integer);
//阻塞方式读取数据(如果是对话,那么上面的byte数组的大小可以适当增加,比如加到 2048,视情况而定
//String s = new String(integer,"utf-8"); 这种方式可以获取字符串字节
i = (integer[0] & 0xff) << 24 |
(integer[1] & 0xff) << 16 |
(integer[2] & 0xff) << 8 |
(integer[3] & 0xff);
System.out.println("获得客户端信息:" + i);
i++;
//outputStream.write(s.getBytes("utf-8"));写入输出流
outputStream.write( new byte[] {
(byte) ((i >> 24) & 0xFF),
(byte) ((i >> 16) & 0xFF),
(byte) ((i >> 8) & 0xFF),
(byte) (i & 0xFF)
});
//清空缓冲区
outputStream.flush();
System.out.println("向客户端发送:" + i);
}
}catch(Exception e){
}
}).start();
}
}
}