简单实现 服务器与客户端的聊天 使用 TCP通信
- 先了解服务器与客户端交互是如何实现的
- 代码实现
- 聊天效果截图
一、先了解TCP通信中 服务器与客户端交互是如何实现的:
二:代码实现:
- 服务器端类:ServerSocket.java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;//服务器套接字
import java.net.Socket;
/**
* TCP通信得服务器端
*
* @author 轩xuan
*
*/
public class TCPServer {
public static void main(String[] args) throws IOException {
ServerSocket serversocket = null;
try {
serversocket = new ServerSocket(8880);
System.out.println("服务器启动成功\n");
} catch (Exception e) {
System.out.println("请先关闭正在运行的程序,释放端口");
}
Socket socket = serversocket.accept();
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
byte[] bytes = new byte[1024];
int i = 0;
while (i < 1000) {
int len = in.read(bytes);
try {// 空字节时退出
out.write(("这是我第" + i++ + "次学客户端说话:\t" + new String(bytes, 0, len) + "\n-------------------------")
.getBytes());
} catch (Exception e) {
System.out.println("客户端取消对话");
break;
}
}
if (i == 1000) {
System.out.println("请求次数已满\n");
}
System.out.println("服务器睡眠");
serversocket.close();
socket.close();
}
}
- 客户端类:TCPClient.java
package tcp通信;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;//客户端类
import java.util.Scanner;
/**
* TCP通信得客户端
*
* @author 轩xuan
*
*/
public class TCPClient {
public static void main(String[] args) throws IOException, Exception {
Socket socket = null;
Scanner sc = new Scanner(System.in);
try {
socket = new Socket("127.0.0.1", 8880);
} catch (Exception e) {
System.out.println("请先启动服务器");
}
OutputStream out = socket.getOutputStream();
InputStream in = socket.getInputStream();
byte[] bytes = new byte[1024];
System.out.println("请输入您想对服务器发送的消息(发送 886 时结束对话)\n");
String str = "521";
while (true) {
System.out.print("\n客户端:");
str = sc.next();
if (str.equals("886")) {
break;
}
out.write(str.getBytes());
int len = in.read(bytes);
System.out.println("服务器:" + new String(bytes, 0, len));
}
out.write("".getBytes());
System.out.println("提示:客户端已经取消对话");
out.close();
socket.close();
sc.close();
}
}
三:实现截图
(为了方便查看具体实现功能,使用两个dos窗口,运行)
《伤心人》---海涅
看到那苍白的少年
人人都要忧心悄悄
因为在他的脸上
铭刻着痛苦和烦恼
充满同情的微风
扇凉他闷热的额角
从前那些冷淡的姑娘
乐意报以宽慰的微笑
他避开市民的喧嚣
一直向森林奔逃
那有树叶在欢鸣
那有小鸟在欢叫
可是当这个伤心人
慢慢地走进森林
鸟儿都停止歌唱
树叶也发出悲鸣