我做了一个,可是只能单向通讯,客户端发给服务端,或者服务端发给客户端,但是实现不了双向的。====================服务端==================================
public class MyServer extends Thread{
private Socket client; //创建客户端socket,与客户端通讯
public MyServer(Socket skt){
this.client = skt;
}
public void run(){
try{
BufferedReader in=new BufferedReader(new InputStreamReader(client.getInputStream())); //创建输入流
PrintWriter out=new PrintWriter(client.getOutputStream()); //创建输出流
BufferedReader serverIn=new BufferedReader(new InputStreamReader(System.in)); //创建本地(服务端)输入流
while(true){
//发送消息
String str = serverIn.readLine(); //读取本地输入的信息
// if(str != null){
out.println(str); //在客户端打印
// }
out.flush();
// 读取消息
String clientstr = in.readLine(); //读取客户端输入的信息
// if(clientstr != null){
System.out.println(clientstr); //在本地打印
out.println("服务端已收到!"); //向客户端发送成功消息
out.flush();
// }
if(clientstr.equals("end")){
System.out.println("客户端已断开!");
break;
}
}
client.close();
}catch(IOException ioe){
System.out.println("ioexception happened!");
}
}
public static void main(String[] args) throws IOException {
ServerSocket server=new ServerSocket(5678); //创建服务器对象,使用5678端口,响应客户端连接 while(true){ //循环开始监听,是否有连接请求
MyServer user = new MyServer(server.accept());
user.start();
}
}
}==========================客户端==============================
public class MyClient { static Socket server; public static void main(String[] args)throws Exception {
//创建socket对象,与服务端通讯
server=new Socket(InetAddress.getLocalHost(),5678);
BufferedReader in=new BufferedReader(new InputStreamReader(server.getInputStream()));
PrintWriter out=new PrintWriter(server.getOutputStream());
BufferedReader clientwt=new BufferedReader(new InputStreamReader(System.in)); //创建本地写入流 while(true){
//发送消息
String str=clientwt.readLine(); //读取本地输入的信息
if(!str.equals("")){
out.println(str); //在服务端打印
}
out.flush();
//读取消息
String serverStr = in.readLine(); //读取服务端输入的信息
// if(serverStr != null){
System.out.println(serverStr); //在本地打印
out.println("客户端已收到!"); //向服务端发送成功消息
out.flush();
// }
if(str.equals("end")){
System.out.println("服务端连接已断开!");
break;
}
System.out.println(in.readLine());
}
server.close();
}
}应该是客户端代码要用线程的问题,不知道怎么用,请高手指点一下~~弄了好久了都没成功。谢谢。
public class MyServer extends Thread{
private Socket client; //创建客户端socket,与客户端通讯
public MyServer(Socket skt){
this.client = skt;
}
public void run(){
try{
BufferedReader in=new BufferedReader(new InputStreamReader(client.getInputStream())); //创建输入流
PrintWriter out=new PrintWriter(client.getOutputStream()); //创建输出流
BufferedReader serverIn=new BufferedReader(new InputStreamReader(System.in)); //创建本地(服务端)输入流
while(true){
//发送消息
String str = serverIn.readLine(); //读取本地输入的信息
// if(str != null){
out.println(str); //在客户端打印
// }
out.flush();
// 读取消息
String clientstr = in.readLine(); //读取客户端输入的信息
// if(clientstr != null){
System.out.println(clientstr); //在本地打印
out.println("服务端已收到!"); //向客户端发送成功消息
out.flush();
// }
if(clientstr.equals("end")){
System.out.println("客户端已断开!");
break;
}
}
client.close();
}catch(IOException ioe){
System.out.println("ioexception happened!");
}
}
public static void main(String[] args) throws IOException {
ServerSocket server=new ServerSocket(5678); //创建服务器对象,使用5678端口,响应客户端连接 while(true){ //循环开始监听,是否有连接请求
MyServer user = new MyServer(server.accept());
user.start();
}
}
}==========================客户端==============================
public class MyClient { static Socket server; public static void main(String[] args)throws Exception {
//创建socket对象,与服务端通讯
server=new Socket(InetAddress.getLocalHost(),5678);
BufferedReader in=new BufferedReader(new InputStreamReader(server.getInputStream()));
PrintWriter out=new PrintWriter(server.getOutputStream());
BufferedReader clientwt=new BufferedReader(new InputStreamReader(System.in)); //创建本地写入流 while(true){
//发送消息
String str=clientwt.readLine(); //读取本地输入的信息
if(!str.equals("")){
out.println(str); //在服务端打印
}
out.flush();
//读取消息
String serverStr = in.readLine(); //读取服务端输入的信息
// if(serverStr != null){
System.out.println(serverStr); //在本地打印
out.println("客户端已收到!"); //向服务端发送成功消息
out.flush();
// }
if(str.equals("end")){
System.out.println("服务端连接已断开!");
break;
}
System.out.println(in.readLine());
}
server.close();
}
}应该是客户端代码要用线程的问题,不知道怎么用,请高手指点一下~~弄了好久了都没成功。谢谢。
import java.io.*;
import java.net.*;
import java.util.*;public class ChatServer {
boolean started = false;
ServerSocket ss = null;
List<Client> clients = new ArrayList<Client>();
public static void main(String[] args) {
new ChatServer().start();
}
public void start() {
try {
ss = new ServerSocket(8888);
started = true;
} catch (BindException e) {
System.out.println("端口使用中....");
System.out.println("请关掉相关程序并重新运行服务器!");
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
}
try {
while(started) {
Socket s = ss.accept();
Client c = new Client(s);
System.out.println("a client connected!");
new Thread(c).start();
clients.add(c);
//dis.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ss.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Client implements Runnable {
private Socket s;
private DataInputStream dis = null;
private DataOutputStream dos = null;
private boolean bConnected = false;
public Client(Socket s) {
this.s = s;
try {
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
bConnected = true;
} catch (IOException e) {
e.printStackTrace();
}
}
public void send(String str) {
try {
dos.writeUTF(str);
} catch (IOException e) {
clients.remove(this);
System.out.println("对方退出了!我从List里面去掉了!");
//e.printStackTrace();
}
}
public void run() {
try {
while(bConnected) {
String str = dis.readUTF();
System.out.println(str);
for(int i=0; i<clients.size(); i++) {
Client c = clients.get(i);
c.send(str);
//System.out.println(" a string send !");
}
/*
for(Iterator<Client> it = clients.iterator(); it.hasNext(); ) {
Client c = it.next();
c.send(str);
}
*/
/*
Iterator<Client> it = clients.iterator();
while(it.hasNext()) {
Client c = it.next();
c.send(str);
}
*/
}
} catch (EOFException e) {
System.out.println("Client closed!");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(dis != null) dis.close();
if(dos != null) dos.close();
if(s != null) {
s.close();
//s = null;
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}客户端:import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;public class ChatClient extends Frame {
Socket s = null;
DataOutputStream dos = null;
DataInputStream dis = null;
private boolean bConnected = false; TextField tfTxt = new TextField(); TextArea taContent = new TextArea();
Thread tRecv = new Thread(new RecvThread()); public static void main(String[] args) {
new ChatClient().launchFrame();
} public void launchFrame() {
setLocation(400, 300);
this.setSize(300, 300);
add(tfTxt, BorderLayout.SOUTH);
add(taContent, BorderLayout.NORTH);
pack();
this.addWindowListener(new WindowAdapter() { @Override
public void windowClosing(WindowEvent arg0) {
disconnect();
System.exit(0);
}
});
tfTxt.addActionListener(new TFListener());
setVisible(true);
connect();
tRecv.start();
}
public void connect() {
try {
s = new Socket("127.0.0.1", 8888);
dos = new DataOutputStream(s.getOutputStream());
dis = new DataInputStream(s.getInputStream());
System.out.println("connected!");
bConnected = true;
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void disconnect() {
try {
dos.close();
dis.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
/*
try {
bConnected = false;
tRecv.join();
} catch(InterruptedException e) {
e.printStackTrace();
} finally {
try {
dos.close();
dis.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
*/
}
private class TFListener implements ActionListener { public void actionPerformed(ActionEvent e) {
String str = tfTxt.getText().trim();
//taContent.setText(str);
tfTxt.setText("");
try {
//System.out.println(s);
dos.writeUTF(str);
dos.flush();
//dos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
private class RecvThread implements Runnable { public void run() {
try {
while(bConnected) {
String str = dis.readUTF();
//System.out.println(str);
taContent.setText(taContent.getText() + str + '\n');
}
} catch (SocketException e) {
System.out.println("退出了,bye!");
} catch (EOFException e) {
System.out.println("推出了,bye - bye!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
TestServer.javaimport java.net.Socket;
import java.net.ServerSocket;
import java.io.IOException;
import java.io.DataInputStream;
import java.util.Date;
import java.io.*;
public class TestServer{
public static void main(String args[]){DataInputStream din=null;
DataOutputStream don=null;
InputStreamReader isr=null;
BufferedReader br=null;
ServerSocket ss=null;
Socket c=null;try{
ss=new ServerSocket(6666);
c=ss.accept();
din=new DataInputStream(c.getInputStream());
isr=new InputStreamReader(System.in);
br=new BufferedReader(isr);while(true){
//..............................
System.out.println(din.readUTF());
//................................String temp=br.readLine();
don=new DataOutputStream(c.getOutputStream());
don.writeUTF(temp);
don.flush();}
}catch(IOException e){
e.getMessage();
}
finally{
try{
if(c!=null){
c.close();
}
if(ss!=null){
ss.close();
}
if(din!=null)
{
din.close();
}
if(don!=null){
don.close();
don=null;
}
if(isr!=null){
isr.close();
isr=null;
}
}catch(IOException e){
e.getMessage();
}
}
}
}
TestSocket.javaimport java.io.*;
import java.net.Socket;
import java.io.IOException;
import java.io.DataOutputStream;
import java.net.UnknownHostException;
import java.io.DataInputStream;
public class TestSocket{//.........................................
public void connection(){
Socket cc=null;
DataOutputStream dout=null;
InputStreamReader isr=null;
BufferedReader br=null;
DataInputStream din=null; try{
isr=new InputStreamReader(System.in);
br=new BufferedReader(isr);
//...............
cc=new Socket("127.0.0.1",6666);
dout=new DataOutputStream(cc.getOutputStream());
din=new DataInputStream(cc.getInputStream());
while(true){
String temp=br.readLine();
dout.writeUTF(temp);
dout.flush();//刷新 String st=din.readUTF();
System.out.println(st);
} }catch(UnknownHostException e){
e.getMessage();
}catch(IOException e){
e.getMessage();
}
finally{
try{
if(cc!=null){
cc.close();
cc.close();
}
if(dout!=null){
dout.close();
dout=null;
}
if(br!=null){
br.close();
br=null;
}
}catch(IOException e){
e.getMessage();
}
}
}
//.........................................public static void main(String args[]){
new TestSocket().connection();
}
}作程序一定要多想,先想好了再做
谢谢,没想到你今天还真给我代码了,意外。。 我已经运行了,如果客户端先发消息给服务端,然后服务端再发给客户端,依次这样,那么这个程序没问题。 但是,
如果是服务端先发消息给客户端,那么客户端收不到,除非客户端再给服务端发消息才能收到。为什么呢? 如果客户端连发两条消息,那么第二条消息服务端就收不到了。。只能收到第一条。怎么回事? 另外,你要方便的话,简单跟我说下原理吧,或者流程,步骤之类的。 可以发我邮箱里,[email protected] 不过真的谢谢你,结贴了,分给你。