怎么在Java中使用Socket编写一个聊天程序?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
服务器端程序Server
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class TestTcpServer {
public static void main(String[] args) {
ServerSocket ss = null;
BufferedReader in = null;
try {
ss = new ServerSocket(8888);
System.out.println("服务器启动");
Socket socket = ss.accept();
System.out.println("连接建立");
System.out.println(socket.getInetAddress().getHostAddress());
//服务器接收客户端发送的数据
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String clientContent = in.readLine();
System.out.println("接收客户端消息: " +clientContent);
} catch (IOException e) {
e.printStackTrace();
}
}
}
客户端程序Clinet
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class TestTcpClient {
public static void main(String[] args) {
Socket socket = null;
BufferedWriter out = null;
//客户端发送数据,服务器端接收
try {
socket = new Socket("127.0.0.1",8888);
System.out.println("与服务器连接了");
Scanner sc = new Scanner(System.in);
String content = sc.nextLine();
out = new BufferedWriter((new OutputStreamWriter(socket.getOutputStream())));
out.write(content);
out.flush();
sc.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
out.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
运行样例
注意要先起S端,否则:

好啦,先起S端:

然后S端就在等待,它“说话”也没人理它:

接着起C端:

S端也会有响应:

然后C端发消息:

S端收到消息,就双双Over了:

看完上述内容,你们掌握怎么在Java中使用Socket编写一个聊天程序的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注天达云行业资讯频道,感谢各位的阅读!