java socket单线程一对一聊天代码问题
CloseTest类是自定义一个关流的方法.问题如下:代码实现一对一,客户端一句话,服务器回一句话。我把读写操作方在while循环里。我想知道读的信息是传到InputSt...
CloseTest类 是自定义一个关流的方法.
问题如下:
代码实现一对一,客户端一句话,服务器回一句话。我把读写操作方在while循环里。
我想知道读的信息是传到InputStream is = socket.getInputStream(); 还是直接传到is?
不太了解交互的信息是怎么跳·
具体代码见下:
服务器:
public static void main(String[] args) throws Exception {
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 6666);
OutputStream os = socket.getOutputStream();
InputStream is = socket.getInputStream();
Scanner scan = new Scanner(System.in);
while(true){
//写
String msg = scan.nextLine();
byte[] b = msg.getBytes();
os.write(b, 0, b.length);
//读
b = new byte[1024];
is.read(b);
msg = new String(b,0,b.length);
System.out.println("来自服务器的消息:"+ msg);
if(msg.equals("bye")){
break;
}
}
CloseTest.closeAll(os,is,scan,socket);
}
=========================================
客户端
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(6666);
System.out.println("服务器在监听");
Socket socket = server.accept();
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
Scanner scan = new Scanner(System.in);
while(true){
//读
String msg = null;
byte[] b = new byte[1024];
is.read(b);
msg = new String(b,0,b.length);
System.out.println("来自客户端的消息:"+ msg);
if(msg.equals("bye")){
break;
}
//写
msg = scan.nextLine();
b = msg.getBytes();
os.write(b,0,b.length);
}
CloseTest.closeAll(is,os,scan,socket,server);
} 展开
问题如下:
代码实现一对一,客户端一句话,服务器回一句话。我把读写操作方在while循环里。
我想知道读的信息是传到InputStream is = socket.getInputStream(); 还是直接传到is?
不太了解交互的信息是怎么跳·
具体代码见下:
服务器:
public static void main(String[] args) throws Exception {
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 6666);
OutputStream os = socket.getOutputStream();
InputStream is = socket.getInputStream();
Scanner scan = new Scanner(System.in);
while(true){
//写
String msg = scan.nextLine();
byte[] b = msg.getBytes();
os.write(b, 0, b.length);
//读
b = new byte[1024];
is.read(b);
msg = new String(b,0,b.length);
System.out.println("来自服务器的消息:"+ msg);
if(msg.equals("bye")){
break;
}
}
CloseTest.closeAll(os,is,scan,socket);
}
=========================================
客户端
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(6666);
System.out.println("服务器在监听");
Socket socket = server.accept();
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
Scanner scan = new Scanner(System.in);
while(true){
//读
String msg = null;
byte[] b = new byte[1024];
is.read(b);
msg = new String(b,0,b.length);
System.out.println("来自客户端的消息:"+ msg);
if(msg.equals("bye")){
break;
}
//写
msg = scan.nextLine();
b = msg.getBytes();
os.write(b,0,b.length);
}
CloseTest.closeAll(is,os,scan,socket,server);
} 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询