一、创建新项目
首先创建一个新的项目,并命名为聊天。然后创建包,创建两个类,客户端(SocketClient)和服务器端(SocketServer)
二、实现代码
客户端代码:
package 聊天;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;
public class SocketClient {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
Socket client = new Socket("localhost", 6666);
while (true) {
OutputStream out = client.getOutputStream();
//从控制台输入
System.out.println("客户端发送数据");
String str = input.next();
out.write(str.getBytes());
// System.out.println("信息发送成功"+str);
if (str.equals("over")) {
System.out.println("客户端已关闭");
out.close();
client.close();
break;
}
//-------------------客户器端读取回复信息----------------------//
InputStream in = client.getInputStream();
byte[] b = new byte[1024];
int len = in.read(b);
//接收到的数据
String info = new String(b, 0, len);
System.out.println("这是从客户端接收的数据:" + info);
}
}
}
服务器端代码:
package 聊天;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class SocketServer {
public static void main(String[] args) throws Exception {
System.out.println("服务器端启动,等待连接--------------");
//1.创建ServerSocket对象,绑定端口,开始等待连接
ServerSocket ss = new ServerSocket(6666);
//2.接受连接,accept方法,返回Socket对象
Socket server = ss.accept();
while (true) {
InputStream in = server.getInputStream();
byte[] b = new byte[1024];
int len = in.read(b);
//接收到的数据
String info = new String(b, 0, len);
System.out.println("这是从客户端接收的数据:" + info);
if (info.equals("over")) {
System.out.println("服务器已关闭");
in.close();
server.close();
break;
}
//-------------------服务器端回复信息----------------------//
System.out.println("服务器回复客户端信息:");
OutputStream out = server.getOutputStream();
//从控制台输入
Scanner input = new Scanner(System.in);
String str = input.next();
out.write(str.getBytes());
}
}
}
三、运行结果
先运行服务器端,然后快速运行客户端,实现如下效果