这是一段Socket点对点聊天的代码,但是运行的时候有时候会出现乱码,还有就是怎么实现客户端或者服务端说两句以上话的功能。新手,编辑的有点乱,求指教
package com.chat2;//这是服务端的代码
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) {
try{
ServerSocket ss=new ServerSocket(9008);
Socket s=ss.accept();
System.out.println(s.getInetAddress().getHostName()+"上线了");
//准备输入流
DataInputStream sin=new DataInputStream(s.getInputStream());
//准备好输出流
DataOutputStream sout=new DataOutputStream(s.getOutputStream());
//准备好两个线程
Thread msr=new ServerReceive(sin);
Thread mss=new ServerSend(sout);
msr.start();
mss.start();
}catch(IOException e){
e.printStackTrace();
}
}
}
//创建一个接受消息的线程
class ServerReceive extends Thread{
private DataInputStream sin;
public ServerReceive (DataInputStream sin){
this.sin=sin;
}
public void run(){
String msg;
try{
while(true){
msg=sin.readUTF();
System.out.println("客户端说:"+msg);
if(msg.equals("bye")){
System.out.println("客户端下线了。系统退出");
System.exit(0);
}
}
}catch(IOException e){
e.printStackTrace();
}
}
}
//创建一个线程写入并发送消息
class ServerSend extends Thread{
private DataOutputStream sout;
public ServerSend(DataOutputStream sout){
this.sout=sout;
}
public void run(){
BufferedReader cin=new BufferedReader(new InputStreamReader(System.in));//准备好键盘输入流
String msg;
try{
while(true){
msg=cin.readLine();
sout.writeUTF(msg);
if(msg.equals("bye")){
System.out.println("服务端自己下线,退出系统");
System.exit(0);
}
}
}catch(IOException e){
e.printStackTrace();
}
}
}
package com.chat2;
//这是客户端的代码
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
try{
String strServerName="zc-pc.";
InetAddress add=InetAddress.getByName(strServerName);
Socket s=new Socket(add,9008);
//准备好输入流
DataInputStream sin=new DataInputStream(s.getInputStream());
//准备好输出流
DataOutputStream sout=new DataOutputStream(s.getOutputStream());
//创建两个线程
Thread msr=new ClientReceive(sin);
Thread mss=new ClientSend(sout);
msr.start();
mss.start();
}catch(IOException e){
e.printStackTrace();
}
}
}
//创建接受消息的线程
class ClientReceive extends Thread{
private DataInputStream sin;
public ClientReceive(DataInputStream sin){
this.sin=sin;
}
public void run(){
String msg;
try{
while(true){
msg=sin.readUTF();
System.out.println("服务端说:"+msg);
if(msg.equals("bye")){
System.out.println("服务端走了,系统退出");
System.exit(0);
}
}
}catch(IOException e){
e.printStackTrace();
}
}
}
//创建一个写入并发送消息的线程
class ClientSend extends Thread{
private DataOutputStream sout;
public ClientSend(DataOutputStream sout){
this.sout=sout;
}
public void run(){
BufferedReader cin=new BufferedReader(new InputStreamReader(System.in));
String msg;
try{
while(true){
msg=cin.readLine();
sout.writeUTF(msg);
if(msg.equals("bye")){
System.out.println("客户端自己下线,程序退出");
System.exit(0);
}
}
}catch(IOException e){
e.printStackTrace();
}
}
} java socket 线程
补充:Java , Java EE