Socket是网络上运行的两个程序间双向通讯的一端,它既可以接受请求,也可以发送请求,利用它可以较为方便的编写网络上的数据的传递。在java中,有专门的socket类来处理用户的请求和响应。利用SOCKET类的方法,就可以实现两台计算机之间的通讯。这里就介绍一下在JAVA中如何利用socket进行网络编程。 在Java中Socket可以理解为客户端或者服务器端的一个特殊的对象,这个对象有两个关键的方法,一个是getInputStream方法,另一个是getOutputStream方法。getInputStream方法可以得到一个输入流,客户端的Socket对象上的getInputStream方法得到的输入流其实就是从服务器端发回的数据流。GetOutputStream方法得到一个输出流,客户端Socket对象上的getOutputStream方法返回的输出流就是将要发送到服务器端的数据流,(其实是一个缓冲区,暂时存储将要发送过去的数据)。 程序可以对这些数据流根据需要进行进一步的封装。本文的例子就对这些数据流进行了一定的封装(关于封装可以参考Java中流的实现部分)。 一、建立服务器类 Java中有一个专门用来建立Socket服务器的类,名叫ServerSocket,可以用服务器需要使用的端口号作为参数来创建服务器对象。ServerSocket server = new ServerSocket(9998) 这条语句创建了一个服务器对象,这个服务器使用9998号端口。当一个客户端程序建立一个Socket连接,所连接的端口号为9998时,服务器对象server便响应这个连接,并且server.accept()方法会创建一个Socket对象。服务器端便可以利用这个Socket对象与客户进行通讯。Socket incoming = server.accept() 进而得到输入流和输出流,并进行封装BufferedReader in = new BufferedReader(new InputStreamReader(incoming.getInputStream())); PrintWriter out = new PrintWriter(incoming.getOutputStream(),true); 随后,就可以使用in.readLine()方法得到客户端的输入,也可以使用out.println()方法向客户端发送数据。从而可以根据程序的需要对客户端的不同请求进行回应。
Ⅱ java网络编程问题
1.每个客户端上线的时候都会把自己的IP传给服务器,服务器会维护一个QQ号码与对应IP的列表。
2.
A如果想给B发消息,首先要去服务器上通过B的QQ号查询B的IP,然后与B建立P2P的通信,不怎能是每次通讯都经过服务器的,那样服务器的负载就太重了,肯定没法即时响应。
Ⅲ 求一个用JAVA写的网络编程的网络聊天系统,能够实现两个人聊天信息收发。
这个是客户端
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
public class client extends Frame implements ActionListener{
int i=1;Frame f;
TextField ip,port;
Label Lip,Lport;
Button connect,exit;
public static void main(String args[])
{client c1 = new client();
c1.init();
}
public void init()
{
f=new Frame("client connection");
f.setLayout(new FlowLayout());
ip =new TextField("localhost");
port =new TextField("8189",5);
Lip=new Label("ip address");
Lport=new Label("port");
connect=new Button("connect");
exit=new Button("exit");
connect.addActionListener(this);
exit.addActionListener(this);
f.add(Lip);
f.add(ip);
f.add(Lport);
f.add(port);
f.add(connect);
f.add(exit);
f.setSize(500,60);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==exit)
System.exit(0);
if(e.getSource()==connect)
{
new Thread(new threadclient(ip.getText(),port.getText(),i)).start();
i++;
}
}
}
class threadclient extends Frame implements Runnable,ActionListener{
String ip,port;
int no;
Frame f;
TextArea ta;
TextArea name;
TextField tf;
Button send,bye;
InputStream ins;
Socket s;
PrintStream out1;
BufferedReader in;
BufferedWriter out;
threadclient(String n,String m,int i)
{
ip=n;
port=m;
no=i;
}
public void run(){
f=new Frame("client NO." +no);
f.setLayout(new FlowLayout());
ta=new TextArea("",10,30,TextArea.SCROLLBARS_BOTH);
tf=new TextField("",20);
send=new Button("send");
bye=new Button("bye");
send.addActionListener(this);
bye.addActionListener(this);
f.add(ta);
f.add(tf);
f.add(send);
f.add(bye);
f.setSize(300,300);
f.setVisible(true);
Integer tmp=new Integer(port);
int portint =tmp.intValue();
try
{
s=new Socket(ip,portint);
in=new BufferedReader(new InputStreamReader(s.getInputStream()));
out1=new PrintStream(s.getOutputStream());
ta.append(in.readLine()+"\n");
}catch(Exception e)
{
System.out.println(e.getMessage()+" ss");
}
}
public void send(String txt){
try{
out1.println(txt);
out1.flush();
ta.append(in.readLine()+"\n");
}catch(IOException e)
{
System.out.println(e.getMessage()+"send");
}
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==bye){
send("BYE");
System.exit(0);
}
if (e.getSource()==send)
send(tf.getText());
}
}
这个是服务器
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
public class server {
private static Map<String,Socket> clientMap=new HashMap<String,Socket>();
public static void main(String[] args) {
int i = 1;
try {
ServerSocket s = new ServerSocket(8189);
for (;;) {
Socket incoming = s.accept();
System.out.println("连接成功" + i);
ThreadedEchoHandler teh=new ThreadedEchoHandler(incoming, i);
teh.start();
String name=teh.getClientname();
clientMap.put(name,incoming);
i++;
}
} catch (Exception e) {
System.out.println(e);
}
}
}
class ThreadedEchoHandler extends Thread {
Frame f;
TextArea ta;
TextField tf;
Button send, bye;
InputStream ins;
Socket s;
PrintStream out1;
BufferedReader in;
PrintWriter out;
public ThreadedEchoHandler(Socket i, int c) {
incoming = i;
counter = c;
f=new Frame("server");
f.setLayout(new FlowLayout());
ta=new TextArea("",10,30,TextArea.SCROLLBARS_BOTH);
tf=new TextField("",20);
send=new Button("send");
bye=new Button("bye");
send.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
send(tf.getText());
}
});
bye.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
send("bye");
}
});
f.add(ta);
f.add(tf);
f.add(send);
f.add(bye);
f.setSize(300,300);
f.setVisible(true);
}
public String getClientname() {
try {
in = new BufferedReader(new InputStreamReader(
incoming.getInputStream()));
out = new PrintWriter(incoming.getOutputStream(), true);
return in.readLine();
} catch (IOException e) {
System.out.println(e.getMessage()+"get");
}
return null;
}
public void send(String context){
out.println(context);
out.flush();
}
public void run() {
try {
boolean done = false;
while (!done) {
String str = in.readLine();
if (str == null)
done = true;
else {
out.println("Echo(" + counter + "):" + str);
ta.append("Echo(" + counter + "):" + str+"\n");
if (str.trim().equals("BYE"))
done = true;
}
}
incoming.close();
} catch (Exception e) {
System.out.println(e.getMessage()+"run");
}
}
private Socket incoming;
private int counter;
}
这个鸟东西是个新手写的。唉,太烂了,我无力吐槽。
Ⅳ 我要一份用java网络编程写的点对点的两人聊天程序(TCP和UDP)
Server端:
import java.io.*;
import java.net.*;
import java.applet.Applet;
public class TalkServer{
public static void main(String args[]) {
try{
ServerSocket server=null;
try{
server=new ServerSocket(4700);
}catch(Exception e) {
System.out.println("can not listen to:"+e);
}
Socket socket=null;
try{
socket=server.accept();
}catch(Exception e) {
System.out.println("Error."+e);
}
String line;
BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter os=new PrintWriter(socket.getOutputStream());
BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Client:"+is.readLine());
line=sin.readLine();
while(!line.equals("bye")){
os.println(line);
os.flush();
System.out.println("Server:"+line);
System.out.println("Client:"+is.readLine());
line=sin.readLine();
}
os.close();
is.close();
socket.close();
server.close();
}catch(Exception e){
System.out.println("Error:"+e);
}
}
}
Client端:
import java.io.*;
import java.net.*;
public class TalkClient {
public static void main(String args[]) {
try{
Socket socket=new Socket("127.0.0.1",4700);
BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));
PrintWriter os=new PrintWriter(socket.getOutputStream());
BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream()));
String readline;
readline=sin.readLine(); //从系统标准输入读入一字符串
while(!readline.equals("bye")){
os.println(readline);
os.flush();
System.out.println("Client:"+readline);
System.out.println("Server:"+is.readLine());
readline=sin.readLine(); //从系统标准输入读入一字符串
}
os.close(); //关闭Socket输出流
is.close(); //关闭Socket输入流
socket.close(); //关闭Socket
}catch(Exception e) {
System.out.println("Error"+e); //出错,则打印出错信息
}
}
}
Ⅳ 用JAVA 编写简单网络聊天程序
/**
* 基于UDP协议的聊天程序
*
* 2007.9.18
* */
//导入包
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.net.*;
public class Chat extends JFrame implements ActionListener
{
//广播地址或者对方的地址
public static final String sendIP = "172.18.8.255";
//发送端口9527
public static final int sendPort = 9527;
JPanel p = new JPanel();
List lst = new List(); //消息显示
JTextField txtIP = new JTextField(18); //填写IP地址
JTextField txtMSG = new JTextField(20); //填写发送消息
JLabel lblIP = new JLabel("IP地址:");
JLabel lblMSG = new JLabel("消息:");
JButton btnSend = new JButton("发送");
byte [] buf;
//定义DatagramSocket的对象必须进行异常处理
//发送和接收数据报包的套接字
DatagramSocket ds = null;
//=============构造函数=====================
public Chat()
{
CreateInterFace();
//注册消息框监听器
txtMSG.addActionListener(this);
btnSend.addActionListener(this);
try
{
//端口:9527
ds =new DatagramSocket(sendPort);
}
catch(Exception ex)
{
ex.printStackTrace();
}
//============接受消息============
//匿名类
new Thread(new Runnable()
{
public void run()
{
byte buf[] = new byte[1024];
//表示接受数据报包
while(true)
{
try
{
DatagramPacket dp = new DatagramPacket(buf,1024,InetAddress.getByName(txtIP.getText()),sendPort);
ds.receive(dp);
lst.add("【消息来自】◆" + dp.getAddress().getHostAddress() + "◆"+"【说】:" + new String (buf,0,dp.getLength()) /*+ dp.getPort()*/,0);
}
catch(Exception e)
{
if(ds.isClosed())
{
e.printStackTrace();
}
}
}
}
}).start();
//关闭窗体事件
this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent w)
{
System.out.println("test");
int n=JOptionPane.showConfirmDialog(null,"是否要退出?","退出",JOptionPane.YES_NO_OPTION);
if(n==JOptionPane.YES_OPTION)
{
dispose();
System.exit(0);
ds.close();//关闭ds对象//关闭数据报套接字
}
}
});
}
//界面设计布局
public void CreateInterFace()
{
this.add(lst,BorderLayout.CENTER);
this.add(p,BorderLayout.SOUTH);
p.add(lblIP);
p.add(txtIP);
p.add(lblMSG);
p.add(txtMSG);
p.add(btnSend);
txtIP.setText(sendIP);
//背景颜色
lst.setBackground(Color.yellow);
//JAVA默认风格
this.setUndecorated(true);
this.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
this.setSize(600,500);
this.setTitle("〓聊天室〓");
this.setResizable(false);//不能改变窗体大小
this.setLocationRelativeTo(null);//窗体居中
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
this.setVisible(true);
txtMSG.requestFocus();//消息框得到焦点
}
//===============================Main函数===============================
public static void main(String[]args)
{
new Chat();
}
//================================发送消息===============================
//消息框回车发送消息事件
public void actionPerformed(ActionEvent e)
{
//得到文本内容
buf = txtMSG.getText().getBytes();
//判断消息框是否为空
if (txtMSG.getText().length()==0)
{
JOptionPane.showMessageDialog(null,"发送消息不能为空","提示",JOptionPane.WARNING_MESSAGE);
}
else{
try
{
InetAddress address = InetAddress.getByName(sendIP);
DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName(txtIP.getText()),sendPort);
ds.send(dp);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
txtMSG.setText("");//清空消息框
//点发送按钮发送消息事件
if(e.getSource()==btnSend)
{
buf = txtMSG.getText().getBytes();
try
{
DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName(txtIP.getText()),sendPort);
}
catch(Exception ex)
{
ex.printStackTrace();
}
txtMSG.setText("");//清空消息框
txtMSG.requestFocus();
}
}
}
Ⅵ 想用Java web实现在线聊天,求大神指点。
这个只有通过客户端向服务器主动请求的方式实现,因为http协议是无状态的一次请求结束之后,服务器就没法再找到客户端的浏览器了,所以只能是客户端定期到服务器查询有无新消息。消息页面的弹出可以使用js实现。打开多个相同页面可能会同时都弹出吧,这个我不太清楚,不过一般很少有人会去开多个页面吧。至于服务器压力的问题,我觉得应该不是什么大问题,因为每次请求的数据量也不是很大,你可以将请求时间间隔设置的长一点。希望我的回答能对你有帮助。
Ⅶ JAVA编局域网聊天室
我是用多播实现的,MulticastSocket是DatagramSocket的子类,暂时还只能用于局域网,不过多播是可以在广域网上进行的
大概步骤如下:
1.加入多播组
2.发送/接收数据包
发送需要从文本输入
接收时使用了一个线程循环接收
3.发生异常离开多播组
我也见过用ServerSocket,Socket实现的,随便找本网络编程的书,上面都有类似的代码
编程环境:JDK1.7,eclipse3.5
Ⅷ java网络编程 实现极简单的聊天功能
在同一局域网环境是 应该是可以的! 程序里面只要将Beijing.java里的IP地址改为Shanghai这台机器的地址 ,Shanghai.java里的IP地址改为Beijing这台机器的地址,应该就OK
Ⅸ java网络编程可以一个客户端分多个线程通讯吗。类似于QQ一边聊天一边发送文件
可以啊,完全没问题啊