java中Socket通信

请问如何Client-A向Server发送信息,Server将信息发给Client-B?请贴出代码,我加高分,谢谢2楼的程序执行applet登陆的时候会报连接异常... 请问如何Client-A向Server发送信息,Server将信息发给Client-B?请贴出代码,我加高分,谢谢
2楼的程序执行applet登陆的时候会报连接异常
展开
 我来答
pujia12345
推荐于2016-09-10 · TA获得超过3680个赞
知道大有可为答主
回答量:3456
采纳率:0%
帮助的人:2973万
展开全部
你加了高分我才贴
----------------具体是: Client-A发送消息向Server:消息包括内容+流向(Client-B的地址)+消息来源地址 Server接收后再把消息+来源地址发给Client-B
Raymondguo008
2009-05-04 · TA获得超过1634个赞
知道小有建树答主
回答量:887
采纳率:100%
帮助的人:477万
展开全部
两个文件都给你
肯定没有错的

//ChatServer.java

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();
}

}
}

}
}

//ChatClient.java

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();
}

}

}
}
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
fangliangliang
2009-05-03 · TA获得超过1624个赞
知道小有建树答主
回答量:767
采纳率:0%
帮助的人:651万
展开全部
看看这个怎么样:
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import ccit.Message;

public class Server extends Thread
{
public static final int PORT = 1112;
Socket socket;
ServerSocket serverSocket;

static Vector usrList=new Vector(1,1);

public Server()
{
try
{
serverSocket=new ServerSocket(PORT);
}
catch(IOException ioe)
{
System.out.println("Can't set up server socket."+ioe);
}
System.out.println("server start ...");
this.start();
}
public void run()
{
try
{
while (true)
{
System.out.println("正在等待连接.....");
socket = serverSocket.accept();
//PrintWriter pw=new PrintWriter(socket.getOutputStream());
// pw.println("aaa");
usrThread ut=new usrThread(socket);
usrList.addElement(ut);
}
}
catch(IOException ioe1)
{
System.out.println("Can't set up user thread"+ioe1);
}
}

public static void main(String args[])
{
Server sobj=new Server();

}
}

class usrThread extends Thread
{
Socket socket;
ObjectInputStream osFromClient;
ObjectOutputStream osToClient;

thPut tp;
thGet tg;

static int msgCount=0;
static Vector msgBox = new Vector(1,1);

int localCount=0;

public synchronized void writeMsg(Message msg)
{
msgBox.addElement(msg);
msgCount++;

}
public synchronized Message readMsg()
{
Message msg=(Message)(msgBox.elementAt(localCount));
return msg;
}

public usrThread(Socket s)
{
socket=s;
try
{
osFromClient=new ObjectInputStream(socket.getInputStream());
osToClient=new ObjectOutputStream(socket.getOutputStream());
System.out.println("osToClient and osFromClient finished!");

this.start();
tp=new thPut();
tp.start();
tg=new thGet();
tg.start();
}
catch(Exception e)
{
System.out.println("usrThread init error! "+e);

}

}
public void run()
{

}
class thPut extends Thread
{
Message msg;

public void run()
{
try
{
while(true)
{
msg = (Message)osFromClient.readObject();
writeMsg(msg);
System.out.println(msg.fromname+" says: "+msg.message);
}
}
catch(Exception e)
{
System.out.println("Receive error"+e);
}
}

}

class thGet extends Thread
{
//Declare the currnet message get from readMsg method
Message msg=new Message();
public void run()
{
try
{
while(true)
{

while (localCount>=msgCount)
{
this.sleep(1);
}
msg=readMsg();
System.out.println("Write to "+msg.toname);
osToClient.writeObject(msg);

System.out.println(String.valueOf(localCount));
localCount++;
}

}
catch(Exception e)
{
System.out.println("cant write msg to client"+e);

}
}

}

}
客户端代码:
import java.io.*;
import java.net.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import ccit.Message;

public class ClientChat extends JFrame
{

static long sum;
JLabel lpublic=new JLabel("公共聊天区");
JLabel lprivate=new JLabel("私人聊天区");
JLabel lgetlist=new JLabel("在线用户");

JTextArea taPublicMsg=new JTextArea(10,15);
JTextArea taPrivateMsg=new JTextArea(6,10);

JTextField tfSendMsg=new JTextField(40);

JButton bsend=new JButton("发送");
JButton bexit=new JButton("退出");

JPanel pLabelPub=new JPanel();
JPanel pLabelPri=new JPanel();

Vector userVector=new Vector(1,1);

JList userList=new JList();

Socket socket=null;

String name;

ObjectOutputStream oos=null;
ObjectInputStream ois=null;

public ClientChat(String name)
{

JScrollPane scrpPub=new JScrollPane(taPublicMsg);
pLabelPub.setLayout(new BorderLayout());
pLabelPub.add(lpublic,BorderLayout.NORTH);
pLabelPub.add(scrpPub,BorderLayout.CENTER);

JScrollPane scrpPri=new JScrollPane(taPrivateMsg);
pLabelPri.setLayout(new BorderLayout());
pLabelPri.add(lprivate,BorderLayout.NORTH);
pLabelPri.add(scrpPri,BorderLayout.CENTER);

JPanel pGetMsg=new JPanel();
pGetMsg.setLayout(new GridLayout(3,1,5,5));
pGetMsg.add(pLabelPub);
//pGetMsg.add(taPublicMsg);
pGetMsg.add(pLabelPri);
//pGetMsg.add(taPrivateMsg);

JPanel pSendMsg=new JPanel();
pSendMsg.setLayout(new FlowLayout());
pSendMsg.add(tfSendMsg);
pSendMsg.add(bsend);
pSendMsg.add(bexit);

pGetMsg.add(pSendMsg);

userVector.addElement("To All");
userList.setListData(userVector);
JScrollPane scrpList=new JScrollPane(userList);

JPanel pGetList=new JPanel();
pGetList.setLayout(new BorderLayout());
pGetList.add(lgetlist,BorderLayout.NORTH);
pGetList.add(scrpList,BorderLayout.CENTER);

this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(pGetMsg,BorderLayout.CENTER);
this.getContentPane().add(pGetList,BorderLayout.EAST);
this.setTitle("小桥流水(花语)聊天室(在线用户"+(++sum)+"位)");
this.setSize(500,300);
this.setVisible(true);

this.name=name;
//this.socket=socket;

try
{
System.out.println("正在连接.....");
InetAddress addr = InetAddress.getByName(null);
System.out.println("addr = " + addr);

//socket = new Socket(addr,Server.PORT);
//socket = new Socket("127.0.0.1",1112);

ois=new ObjectInputStream(socket.getInputStream());
oos=new ObjectOutputStream(socket.getOutputStream());

//PrintWriter pw=new PrintWriter(oos);

Message msgLogin=new Message("To All",name,"Login","Login");

//pw.print(msgLogin);
oos.writeObject(msgLogin);
new manageThread().start();

}
catch(Exception e)
{
System.out.println("JFtame error:"+e);
}
}

public class sendListener implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
Message getMsg=new Message();
getMsg.toname=userList.getSelectedValue().toString();
getMsg.fromname=name;
getMsg.message=tfSendMsg.getText();
getMsg.command="chat";
try
{
oos.writeObject(getMsg);
}
catch(Exception e)
{
System.out.println("Send:"+getMsg.message);
}
}
}

public class exitListener implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
Message getMsg=new Message("To All",name,"","Logout");
try
{
oos.writeObject(getMsg);
}
catch(Exception e)
{
System.out.println(e);
}
ClientChat.this.setVisible(false);
}
}

public class manageThread extends Thread
{
Message GetMessage;
public void run()
{
while(true)
{
try
{
GetMessage=(Message)ois.readObject();
if(GetMessage.command.equals("Login"))
{
userVector.addElement(GetMessage.fromname);
userList.setListData(userVector);
taPublicMsg.append(GetMessage.fromname+"has arrived!\n");
}

if(GetMessage.command.equals("Logout"))
{
int i=0;
for(i=0;i<userVector.size();i++)
{
if(((String)userVector.elementAt(i)).equals(GetMessage.fromname))
{
System.out.println("i="+i);
break;
}
}
if(i<userVector.size())
{
userVector.removeElementAt(i);
userList.updateUI();
}
taPublicMsg.append(GetMessage.fromname+"has left!\n");
}

if(GetMessage.command.equals("chat"))
{
if(GetMessage.toname.equals(name))
{
taPrivateMsg.append(GetMessage.fromname+"say to me:"+GetMessage.message+"\n");
}
else
{
taPublicMsg.append(GetMessage.fromname+"say to all:"+GetMessage.message+"\n");
}
}
}
catch(Exception e)
{
System.out.println("GetMessage error:"+e);
break;
}

}
}

}
/* public static void main(String args[])
{
Socket socket=null;
new ClientChat(socket,"all");
}*/

}

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.net.*;
import ccit.Message;
public class ClientLogin extends JApplet
{
JLabel lname=new JLabel("用户名:");
JLabel lpasswd=new JLabel("密 码:");
JTextField tname=new JTextField(10);
JTextField tpasswd=new JTextField(10);
JButton blogin=new JButton("登录");
//Socket socket=null;
public void init()
{
JPanel pup=new JPanel();
JPanel pdown=new JPanel();

pup.setLayout(new GridLayout(2,2,5,5));
pup.add(lname);
pup.add(tname);
pup.add(lpasswd);
pup.add(tpasswd);

pdown.setLayout(new FlowLayout());
pdown.add(blogin);

blogin.addActionListener(new loginListener());

this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(pup,BorderLayout.CENTER);
this.getContentPane().add(pdown,BorderLayout.SOUTH);
}

public class loginListener implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
if(evt.getSource()==blogin)
{
try
{
//Socket socket=new Socket(InetAddress.getLocalHost(),7000);
Socket socket=new Socket("127.0.0.1",1112);
ClientChat customer=new ClientChat(tname.getText());
}
catch(Exception e)
{
System.out.println("Client error:"+e);
return;
}
}
}
}
}

package ccit;
import java.io.*;
public class Message implements Serializable
{
public String toname;
public String fromname;
public String message;
public String command;

public Message()
{

}
public Message(String to,String from,String msg,String command)
{
this.toname=to;
this.fromname=from;
this.message=msg;
this.command=command;
}

}

客户端要在Applet运行的。
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
收起 1条折叠回答
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式