服务端和客户端互聊
Posted chinaifae
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了服务端和客户端互聊相关的知识,希望对你有一定的参考价值。
package
socket;
import
java.io.DataInputStream;
import
java.io.DataOutputStream;
import
java.io.IOException;
import
java.io.InputStream;
import
java.io.OutputStream;
import
java.net.ServerSocket;
import
java.net.Socket;
import
java.util.Scanner;
public
class
Server {
public
static
void
main(String[] args) {
try
{
ServerSocket ss =
new
ServerSocket(
8888
);
System.out.println(
"监听在端口号:8888"
);
Socket s = ss.accept();
InputStream is = s.getInputStream();
DataInputStream dis =
new
DataInputStream(is);
OutputStream os = s.getOutputStream();
DataOutputStream dos =
new
DataOutputStream(os);
while
(
true
) {
String msg = dis.readUTF();
System.out.println(
"收到客户端信息"
+msg);
Scanner sc =
new
Scanner(System.in);
String str = sc.next();
dos.writeUTF(str);
}
}
catch
(IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package
socket;
import
java.io.DataInputStream;
import
java.io.DataOutputStream;
import
java.io.IOException;
import
java.io.InputStream;
import
java.io.OutputStream;
import
java.net.Socket;
import
java.net.UnknownHostException;
import
java.util.Scanner;
public
class
Client {
public
static
void
main(String[] args) {
try
{
Socket s =
new
Socket(
"127.0.0.1"
,
8888
);
OutputStream os = s.getOutputStream();
DataOutputStream dos =
new
DataOutputStream(os);
InputStream is = s.getInputStream();
DataInputStream dis =
new
DataInputStream(is);
while
(
true
){
Scanner sc =
new
Scanner(System.in);
String str = sc.next();
dos.writeUTF(str);
String msg = dis.readUTF();
System.out.println(
"收到服务端信息"
+msg);
}
}
catch
(UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch
(IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
以上是关于服务端和客户端互聊的主要内容,如果未能解决你的问题,请参考以下文章
Netty入门——springboot框架开发一个简单的服务器端和客户端