java中Socket通信
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java中Socket通信相关的知识,希望对你有一定的参考价值。
请问如何Client-A向Server发送信息,Server将信息发给Client-B?请贴出代码,我加高分,谢谢
2楼的程序执行applet登陆的时候会报连接异常
----------------具体是: Client-A发送消息向Server:消息包括内容+流向(Client-B的地址)+消息来源地址 Server接收后再把消息+来源地址发给Client-B 参考技术A 两个文件都给你
肯定没有错的
//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();
参考技术B 看看这个怎么样:
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运行的。
Java中Socket 实现最简单的客户端与服务端通信
Java中Socket 实现最简单的客户端与服务端通信
引言:因为最近项目中要接入某通信协议接口,基于TCP/IP的socket接口。于是就在本地弄一个最简单的Socket 通信仅供学习。话不多说,直接开摆
客户端代码
package test; import java.io.*; import java.net.Inet4Address; import java.net.InetSocketAddress; import java.net.Socket; public class Client //java基础类方法的入口 public static void main(String[] args)throws IOException Socket socket=new Socket(); //读取流超时的时间设置为3000 socket.setSoTimeout(3000); //连接本地,端口2000;超时时间3000ms socket.connect(new InetSocketAddress(Inet4Address.getLocalHost(), 2000),3000); System.out.println("发起服务器连接---------"); System.out.println("客户端信息:"+socket.getLocalAddress()+" P:"+socket.getLocalPort());//打印本地服务器地址和本地端口号 System.out.println("服务端信息:"+socket.getInetAddress()+" P:"+socket.getPort()); try //发送接收数据 todo(socket); catch (Exception e) System.out.println("出现异常关闭啦"); //释放资源 socket.close(); System.out.println("再见,客户端已退出"); //发送数据的方法 private static void todo(Socket client) throws IOException //构建键盘输入流 InputStream in=System.in; //把键盘输入流转换为BufferedReader BufferedReader input=new BufferedReader(new InputStreamReader(in,"UTF-8")); //得到Socket输出流(Client要发送出去给服务器的信息),并转换为打印流 OutputStream outputStream = client.getOutputStream(); PrintStream socketPrintStream=new PrintStream(outputStream); //得到Socket输入流(Server回复传入Client的信息),并转换为BufferedReader InputStream inputStream = client.getInputStream(); BufferedReader socketBufferedReader=new BufferedReader(new InputStreamReader(inputStream,"UTF-8")); //判断Server是否想要退出,回复“bye”时是他想要结束对话 boolean flag=true; do //键盘读取一行 String str = input.readLine(); //发送到服务器,(通俗就是显示在输入处,在键盘上输入什么,屏幕显示什么) //String str = "003099999920220614100000M1S1C0x0a"; socketPrintStream.println(str); //从服务器读取一行,即Server传入回复给Client的信息 String echo = socketBufferedReader.readLine(); if("bye".equalsIgnoreCase(echo)) flag=false; else //打印到屏幕上,Server回复什么就显示什么 System.out.println("客户端回复:"+echo); while(flag); //资源释放,关闭对于socket资源 socketPrintStream.close(); socketBufferedReader.close();
服务端代码
package test; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.ServerSocket; import java.net.Socket; public class Server public static void main(String[] args)throws IOException ServerSocket server=new ServerSocket(2000); System.out.println("服务器准备就绪----------"); System.out.println("服务器信息:"+server.getInetAddress()+" P:"+server.getLocalPort()); //等待多个客户端连接,循环异步线程 for(;;) //得到客户端 Socket client = server.accept(); //客户端构建异步线程 ClientHandler clientHandler = new ClientHandler(client); //启动线程 clientHandler.start(); /** * 客户端消息处理 */ //多个客户端需要做异步操作,建立异步处理类 private static class ClientHandler extends Thread//线程 private Socket socket;//代表当前的一个连接 private boolean flag=true; ClientHandler(Socket socket) this.socket=socket; //构造方法 //一旦Thead启动起来,就会运行run方法,代表线程启动的部分 @Override public void run() super.run(); //打印客户端的信息 System.out.println("新客户端发起连接:"+socket.getInetAddress()+" P:"+socket.getPort()); //在发送过程中会触发一个IO过程,所以需要捕获异常 try //得到打印流,用于数据输出,服务器回送数据使用,即在屏幕上显示Server要回复Client的信息 PrintStream socketOutput=new PrintStream(socket.getOutputStream()); //得到输入流,用于接收数据,得到Client回复服务器的信息 BufferedReader sockeInput=new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8")); do //客户端回复一条数据 String str = sockeInput.readLine(); if("bye".equalsIgnoreCase(str)) flag=false; //回送 socketOutput.println("bye"); else //打印到屏幕,并回送数据长度 System.out.println(str); socketOutput.println("Server回答说:" +str.length()); while(flag); sockeInput.close(); socketOutput.close(); catch (Exception e) //触发异常时打印一个异常信息 System.out.println("连接异常断开!!!"); finally //连接关闭 try socket.close(); catch (IOException e) e.printStackTrace(); System.out.println("再见,客户端退出:"+socket.getInetAddress()+" P:"+socket.getPort());
然后先运行服务端类Server.java,然后再运行Client.java
在客户端控制台输入任意文字,按下回车键即可。
为人:谦逊、激情、博学、审问、慎思、明辨、 笃行
学问:纸上得来终觉浅,绝知此事要躬行
为事:工欲善其事,必先利其器。
态度:道阻且长,行则将至;行而不辍,未来可期
.....................................................................
------- 换了个头像,静静的想,默默的思恋,一丝淡淡的忧伤 ----------
------- 桃之夭夭,灼灼其华。之子于归,宜其室家。 ---------------
------- 桃之夭夭,有蕡其实。之子于归,宜其家室。 ---------------
------- 桃之夭夭,其叶蓁蓁。之子于归,宜其家人。 ---------------
=====================================================================
转载请标注出处!
学问:纸上得来终觉浅,绝知此事要躬行
为事:工欲善其事,必先利其器。
态度:道阻且长,行则将至;行而不辍,未来可期
.....................................................................
------- 换了个头像,静静的想,默默的思恋,一丝淡淡的忧伤 ----------
------- 桃之夭夭,灼灼其华。之子于归,宜其室家。 ---------------
------- 桃之夭夭,有蕡其实。之子于归,宜其家室。 ---------------
------- 桃之夭夭,其叶蓁蓁。之子于归,宜其家人。 ---------------
=====================================================================
转载请标注出处!
以上是关于java中Socket通信的主要内容,如果未能解决你的问题,请参考以下文章