重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
CS模式的QQ这是服务器:ChatServer.javaimport java.net.*;
10年积累的成都网站建设、成都网站设计经验,可以快速应对客户对网站的新想法和需求。提供各种问题对应的解决方案。让选择我们的客户得到更好、更有力的网络服务。我虽然不认识你,你也不认识我。但先建设网站后付款的网站建设流程,更有昌江黎族免费网站建设让你可以放心的选择与我们合作。
import java.io.*;
public class ChatServer
{
final static int thePort=8189;
ServerSocket theServer;
ChatHandler[] chatters;
int numbers=0;
public static void main(String args[])
{
ChatServer app=new ChatServer();
app.run();
}
public ChatServer()
{
try
{
theServer=new ServerSocket(thePort);
chatters=new ChatHandler[10];
}
catch(IOException io){}
}
public void run()
{
try
{
System.out.println("服务器已经建立!");
while(numbers10)
{
Socket theSocket=theServer.accept();
ChatHandler chatHandler=new ChatHandler(theSocket,this);
chatters[numbers]=chatHandler;
numbers++;
}
}catch(IOException io){}
}
public synchronized void removeConnectionList(ChatHandler c)
{
int index=0;
for(int i=0;i=numbers-1;i++)
if(chatters[i]==c)index=i;
for(int i=index;inumbers-1;i++)
chatters[i]=chatters[i+1];
chatters[numbers-1]=null;
numbers--;
}
public synchronized String returnUsernameList()
{
String line="";
for(int i=0;i=numbers-1;i++)
line=line+chatters[i].user+":";
return line;
}
public void broadcastMessage(String line)
{
System.out.println("发布信息:"+line);
for(int i=0;i=numbers-1;i++)
chatters[i].sendMessage(line);
}
}====================================================这是客户端:ChatClient.javaimport java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.io.*;
public class ChatClient extends Thread implements ActionListener
{
JTextField messageField,IDField,ipField,portField;
JTextArea message,users;
JButton connect,disconnect;
String user="";
String userList[]=new String[10];
Socket theSocket;
BufferedReader in;
PrintWriter out;
boolean connected=false;
Thread thread;
public static void main(String args[])
{
JFrame frame=new JFrame("聊天室");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ChatClient cc=new ChatClient();
JPanel content=cc.createComponents();
frame.getContentPane().add(content);
frame.setSize(550,310);
frame.setVisible(true);
}
public JPanel createComponents()
{
JPanel pane=new JPanel(new BorderLayout());
message=new JTextArea(10,35);
message.setEditable(false);
JPanel paneMsg=new JPanel();
paneMsg.setBorder(BorderFactory.createTitledBorder("聊天内容"));
paneMsg.add(message);
users=new JTextArea(10,10);
JPanel listPanel=new JPanel();
listPanel.setBorder(BorderFactory.createTitledBorder("在线用户:"));
listPanel.add(users);
messageField=new JTextField(50);
IDField=new JTextField(5);
ipField=new JTextField("LocalHost");
portField=new JTextField("8189");
connect=new JButton("连 接");
disconnect=new JButton("断 开");
disconnect.setEnabled(false);
JPanel buttonPanel=new JPanel();
buttonPanel.add(new Label("服务器IP:"));
buttonPanel.add(ipField);
buttonPanel.add(new Label("端口:"));buttonPanel.add(portField);
buttonPanel.add(new Label("用户名:"));
buttonPanel.add(IDField);
buttonPanel.add(connect);
buttonPanel.add(disconnect);
pane.add(messageField,"South");
pane.add(buttonPanel,"North");
pane.add(paneMsg,"Center");
pane.add(listPanel,"West");
connect.addActionListener(this);
disconnect.addActionListener(this);
messageField.addActionListener(this);
IDField.addActionListener(this);
ipField.addActionListener(this);
return pane;
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==connect){
user=IDField.getText();
String ip=ipField.getText();
int port =Integer.parseInt(portField.getText());
if(!user.equals("")connectToServer(ip,port,user))
{
disconnect.setEnabled(true);
connect.setEnabled(false);
}
}
if(e.getSource()==disconnect)disconnectFromServer();
if(e.getSource()==messageField)
if(theSocket!=null)
{
out.println("MESSAGE:"+messageField.getText());
messageField.setText("");
}
}
public void disconnectFromServer()
{
if(theSocket!=null)
{
try
{
connected=false;
out.println("LEAVE:"+user);
disconnect.setEnabled(false);
connect.setEnabled(true);
thread=null;
theSocket.close();
}catch(IOException io){}
theSocket=null;
message.setText("");
users.setText("");
}
}
public boolean connectToServer(String ip,int port,String ID)
{
if(theSocket!=null)
return false;
try
{
theSocket=new Socket(ip,port);
in=new BufferedReader(new InputStreamReader(theSocket.getInputStream()));
out=new PrintWriter(new OutputStreamWriter(theSocket.getOutputStream()),true);
out.println("USER:"+user);
message.setText("");
connected=true;
thread=new Thread(this);
thread.start();
}catch(Exception e){return false;}
return true;
}
public void extractMessage(String line)
{
System.out.println(line);
Message messageline;
messageline=new Message(line);
if(messageline.isValid())
{
if(messageline.getType().equals("JOIN"))
{
user=messageline.getBody();
message.append(user+"进入了聊天室\n");
}
else if(messageline.getType().equals("LIST"))
updateList(messageline.getBody());
else if(messageline.getType().equals("MESSAGE"))
message.append(messageline.getBody()+"\n");
else if(messageline.getType().equals("REMOVE"))
message.append(messageline.getBody()+"离开了聊天室\n");
}
else
message.append("出现问题:"+line+"\n");
}
public void updateList(String line)
{
users.setText("");
String str=line;
for(int i=0;i10;i++)
userList[i]="";
int index=str.indexOf(":");
int a=0;
while(index!=-1){
userList[a]=str.substring(0,index);
str=str.substring(index+1);
a++;
index=str.indexOf(":");
}
for(int i=0;i10;i++)
users.append(userList[i]+"\n");
}
public void run(){
try{
String line="";
while(connected line!=null){
line=in.readLine();
if(line!=null) extractMessage(line);
}
}catch(IOException e){}
}
} =======================================================import java.net.*;
import java.io.*;
class ChatHandler extends Thread{
Socket theSocket;
BufferedReader in;
PrintWriter out;
int thePort;
ChatServer parent;
String user="";
boolean disconnect=false;
public ChatHandler(Socket socket,ChatServer parent){
try{
theSocket=socket;
this.parent=parent;
in=new BufferedReader(new InputStreamReader(theSocket.getInputStream()));
out=new PrintWriter(new OutputStreamWriter(theSocket.getOutputStream()),true);
thePort=theSocket.getPort();
start();
}catch(IOException io){}
}
public void sendMessage(String line){
out.println(line);
}
public void setupUserName(String setname){
user=setname;
//System.out.print(user+"参加");
parent.broadcastMessage("JOIN:"+user);
}
public void extractMessage(String line){
Message messageline;
messageline = new Message(line);
if(messageline.isValid()){
if(messageline.getType().equals("USER")){
setupUserName(messageline.getBody());
parent.broadcastMessage("LIST:"+parent.returnUsernameList());
}
else if(messageline.getType().equals("MESSAGE")){
parent.broadcastMessage("MESSAGE:"+user+"说: "+messageline.getBody());
}
else if(messageline.getType().equals("LEAVE")){
String c=disconnectClient();
parent.broadcastMessage("REMOVE:"+c);
parent.broadcastMessage("LIST:"+parent.returnUsernameList());
}
}
else
sendMessage("命令不存在!");
}
public String disconnectClient(){
try{
in.close();
out.close();
theSocket.close();
parent.removeConnectionList(this);
disconnect=true;
}catch(Exception ex){}
return user;
}
public void run(){
String line,name;
boolean valid=false;
try{
while((line=in.readLine())!=null){
System.out.println("收到:"+line);
extractMessage(line);
}
}catch(IOException io){}
}
}
=========================================================
Message.javapublic class Message{
private String type;
private String body;
private boolean valid;
public Message(String messageLine){
valid=false;
type=body=null;
int pos=messageLine.indexOf(":");
if(pos=0){
type=messageLine.substring(0,pos).toUpperCase();
body=messageLine.substring(pos+1);
valid=true;
}
}
public Message(String type,String body){
valid=true;
this.type=type;
this.body=body;
}
public String getType(){
return type;
}
public String getBody(){
return body;
}
public boolean isValid(){
return valid;
}
} ==================================================共有4个文件,先运行服务段端。。。 这是我以前学的时候写过的!希望能帮的上你
【ClientSocketDemo.java 客户端Java源代码】
import java.net.*;
import java.io.*;
public class ClientSocketDemo
{
//声明客户端Socket对象socket
Socket socket = null;
//声明客户器端数据输入输出流
DataInputStream in;
DataOutputStream out;
//声明字符串数组对象response,用于存储从服务器接收到的信息
String response[];
//执行过程中,没有参数时的构造方法,本地服务器在本地,取默认端口10745
public ClientSocketDemo()
{
try
{
//创建客户端socket,服务器地址取本地,端口号为10745
socket = new Socket("localhost",10745);
//创建客户端数据输入输出流,用于对服务器端发送或接收数据
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
//获取客户端地址及端口号
String ip = String.valueOf(socket.getLocalAddress());
String port = String.valueOf(socket.getLocalPort());
//向服务器发送数据
out.writeUTF("Hello Server.This connection is from client.");
out.writeUTF(ip);
out.writeUTF(port);
//从服务器接收数据
response = new String[3];
for (int i = 0; i response.length; i++)
{
response[i] = in.readUTF();
System.out.println(response[i]);
}
}
catch(UnknownHostException e){e.printStackTrace();}
catch(IOException e){e.printStackTrace();}
}
//执行过程中,有一个参数时的构造方法,参数指定服务器地址,取默认端口10745
public ClientSocketDemo(String hostname)
{
try
{
//创建客户端socket,hostname参数指定服务器地址,端口号为10745
socket = new Socket(hostname,10745);
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
String ip = String.valueOf(socket.getLocalAddress());
String port = String.valueOf(socket.getLocalPort());
out.writeUTF("Hello Server.This connection is from client.");
out.writeUTF(ip);
out.writeUTF(port);
response = new String[3];
for (int i = 0; i response.length; i++)
{
response[i] = in.readUTF();
System.out.println(response[i]);
}
}
catch(UnknownHostException e){e.printStackTrace();}
catch(IOException e){e.printStackTrace();}
}
//执行过程中,有两个个参数时的构造方法,第一个参数hostname指定服务器地址
//第一个参数serverPort指定服务器端口号
public ClientSocketDemo(String hostname,String serverPort)
{
try
{
socket = new Socket(hostname,Integer.parseInt(serverPort));
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
String ip = String.valueOf(socket.getLocalAddress());
String port = String.valueOf(socket.getLocalPort());
out.writeUTF("Hello Server.This connection is from client.");
out.writeUTF(ip);
out.writeUTF(port);
response = new String[3];
for (int i = 0; i response.length; i++)
{
response[i] = in.readUTF();
System.out.println(response[i]);
}
}
catch(UnknownHostException e){e.printStackTrace();}
catch(IOException e){e.printStackTrace();}
}
public static void main(String[] args)
{
String comd[] = args;
if(comd.length == 0)
{
System.out.println("Use localhost(127.0.0.1) and default port");
ClientSocketDemo demo = new ClientSocketDemo();
}
else if(comd.length == 1)
{
System.out.println("Use default port");
ClientSocketDemo demo = new ClientSocketDemo(args[0]);
}
else if(comd.length == 2)
{
System.out.println("Hostname and port are named by user");
ClientSocketDemo demo = new ClientSocketDemo(args[0],args[1]);
}
else System.out.println("ERROR");
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
【ServerSocketDemo.java 服务器端Java源代码】
import java.net.*;
import java.io.*;
public class ServerSocketDemo
{
//声明ServerSocket类对象
ServerSocket serverSocket;
//声明并初始化服务器端监听端口号常量
public static final int PORT = 10745;
//声明服务器端数据输入输出流
DataInputStream in;
DataOutputStream out;
//声明InetAddress类对象ip,用于获取服务器地址及端口号等信息
InetAddress ip = null;
//声明字符串数组对象request,用于存储从客户端发送来的信息
String request[];
public ServerSocketDemo()
{
request = new String[3]; //初始化字符串数组
try
{
//获取本地服务器地址信息
ip = InetAddress.getLocalHost();
//以PORT为服务端口号,创建serverSocket对象以监听该端口上的连接
serverSocket = new ServerSocket(PORT);
//创建Socket类的对象socket,用于保存连接到服务器的客户端socket对象
Socket socket = serverSocket.accept();
System.out.println("This is server:"+String.valueOf(ip)+PORT);
//创建服务器端数据输入输出流,用于对客户端接收或发送数据
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
//接收客户端发送来的数据信息,并显示
request[0] = in.readUTF();
request[1] = in.readUTF();
request[2] = in.readUTF();
System.out.println("Received messages form client is:");
System.out.println(request[0]);
System.out.println(request[1]);
System.out.println(request[2]);
//向客户端发送数据
out.writeUTF("Hello client!");
out.writeUTF("Your ip is:"+request[1]);
out.writeUTF("Your port is:"+request[2]);
}
catch(IOException e){e.printStackTrace();}
}
public static void main(String[] args)
{
ServerSocketDemo demo = new ServerSocketDemo();
}
}
两个类,实现交互
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class MutiChat
{
public static void main(String[] args)
{
MutiChat mc = new MutiChat();
mc.receive().start();
mc.send().start();
}
/**
* 接收信息
*
* @return
*/
private Thread receive()
{
return new Thread()
{
public void run()
{
ServerSocket server_socket = null;
Socket sk = null;
BufferedReader in = null;
try
{
server_socket = new ServerSocket(7777);
sk = server_socket.accept();
in = new BufferedReader(new InputStreamReader(sk
.getInputStream()));
while (true)
{
String str = in.readLine();
System.out.println(str);
}
} catch (Exception e)
{
e.printStackTrace();
}
}
};
}
private Thread send()
{
return new Thread()
{
public void run()
{
Socket client_socket = null;
BufferedReader in = null;
PrintWriter out = null;
while (true)
{
try
{
client_socket = new Socket("127.0.0.1", 8888);
in = new BufferedReader(
new InputStreamReader(System.in));
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(client_socket
.getOutputStream())), true);
while (true)
{
String str = in.readLine();
out.println(str);
}
} catch (Exception e)
{
try
{
Thread.sleep(1000);
} catch (Exception ex)
{
ex.printStackTrace();
}
}
}
}
};
}
}
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class MutiChat2
{
public static void main(String[] args)
{
MutiChat2 mc = new MutiChat2();
mc.receive().start();
mc.send().start();
}
/**
* 接收信息
*
* @return
*/
private Thread receive()
{
return new Thread()
{
public void run()
{
ServerSocket server_socket = null;
Socket sk = null;
BufferedReader in = null;
try
{
server_socket = new ServerSocket(8888);
sk = server_socket.accept();
in = new BufferedReader(new InputStreamReader(sk
.getInputStream()));
while (true)
{
String str = in.readLine();
System.out.println(str);
}
} catch (Exception e)
{
e.printStackTrace();
}
}
};
}
private Thread send()
{
return new Thread()
{
public void run()
{
Socket client_socket = null;
BufferedReader in = null;
PrintWriter out = null;
while (true)
{
try
{
client_socket = new Socket("127.0.0.1", 7777);
in = new BufferedReader(
new InputStreamReader(System.in));
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(client_socket
.getOutputStream())), true);
while (true)
{
String str = in.readLine();
out.println(str);
}
} catch (Exception e)
{
try
{
Thread.sleep(1000);
} catch (Exception ex)
{
ex.printStackTrace();
}
}
}
}
};
}
}
import java.io.*;
import java.net.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;//引入包。
public class ChatClient {
public static void main(String[] args) {
ChatClient cc = new ChatClient();
cc.receive();
}
JTextField jtf; // 文本条
JTextArea jta; //文本域。
Socket s; //客户端
PrintWriter out; //输出流
BufferedReader in; //输入流
public ChatClient() {
JFrame frame = new JFrame("ChatClient");//窗口
frame.setSize(400, 300); //大小
jta = new JTextArea(); //文本域
jta.setEditable(false); //不可编辑
jtf = new JTextField();//文件条
jtf.addActionListener(new ActionListener() { //添加监听。
public void actionPerformed(ActionEvent arg0) {
send(); //调用send()方法
}
});
frame.getContentPane().add(new JScrollPane(jta)); //添加滚动条
frame.getContentPane().add(jtf, "South"); //添加文本条
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关闭窗口。
frame.setVisible(true); //可显示的。
try {
s = new Socket("127.0.0.1", 9000); //连接服务端 socket("主机名",端口号);
in = new BufferedReader(new InputStreamReader(s.getInputStream())); //建立输入流
out = new PrintWriter(s.getOutputStream());//输出流
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void receive() { //接受服务端发来别的客户端的信息。
while (true) {
try {
String text = in.readLine(); //读一行
this.jta.append(text + "\n"); //jta 添加上读入的。
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
}
}
}
public void send() { //发送消息
String text = this.jtf.getText(); //得到你输入的消息
this.jtf.setText(""); //在文本域中显示你输入的消息。
out.println(text); //打印出。
out.flush(); //清空
}
}
Server端
import java.net.*;
import java.io.*;
import java.util.*;//引入包
public class ChatServer {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(9000); //建立服务端,端口号为9000
List list = new ArrayList(); //创建个List集合。
while (true) {
Socket s = ss.accept(); //等待客户端的请求。
list.add(s); //把每一个client都add到集合中去。
Thread t = new ServerThread(s, list); //线程。
t.start(); //启动。
}
}
}
class ServerThread extends Thread {
Socket s;
List list;
BufferedReader in;
PrintWriter out;
public ServerThread(Socket s, List list) { //构造。传入socket和list。
this.s = s;
this.list = list;
try {
in = new BufferedReader(new InputStreamReader(s.getInputStream())); //输入流
out = new PrintWriter(s.getOutputStream()); //输出流
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() { //必须实现其run()方法。
while (true) {
try {
String str = in.readLine(); //得到client端的message。
if (str == null) //如果没有消息就返回。
return;
Iterator it = list.iterator(); //遍历list。
while (it.hasNext()) { //如果list有下一个
Socket socket = (Socket) (it.next()); //因为list中都是存的socket
PrintWriter o = new PrintWriter(socket.getOutputStream()); //输出流
o.println(str); //输出
o.flush(); //清空
}
} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
return;
}
}
}
}
你要的就是点对点通信,见以下例子:
1.简单服务器端
/*
import java.net.*;
import java.io.*;
*/
ServerSocket server=null;
try {
server=new ServerSocket(%%1);
}catch(Exception e){
System.out.println("不能监听:"+e.toString());
}
Socket socket=null;
try {
socket=server.accept();
BufferedReader %%3=new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter %%4=new PrintWriter(socket.getOutputStream());
String %%2=%%3.readLine();
%%4.println("");
%%4.flush();
%%4.close();
%%3.close();
}
catch(IOException e){
System.out.println("出错:"+e.toString());
}finally{
try {
if(socket!=null){
socket.close();
server.close();
}
}
catch(IOException e){
e.printStackTrace();
}
}
2.简单客户端
/*
import java.net.*;
import java.io.*;
*/
Socket socket=null;
try {
socket=new Socket(%%1,%%2);
PrintWriter %%3=new PrintWriter(socket.getOutputStream());
BufferedReader %%4 = new BufferedReader(new InputStreamReader(socket.getInputStream()));
%%3.println("");
%%3.flush();
String %%5=%%4.readLine();
%%6
%%3.close();
%%4.close();
}catch(Exception e){
e.printStackTrace();
}
finally{
try {
socket.close();
}
catch(IOException e){
e.printStackTrace();
}
}
3.获得本机IP
//import java.net.*;
String strIP = null;
try
{
strIP =InetAddress.getLocalHost().getHostAddress().toString();
}
catch(UnknownHostException e)
{
e.printStackTrace();
}
/*
%%1=InetAddress.getLocalHost().getHostAddress();
EnumerationNetworkInterface netInterfaces = null;
try {
netInterfaces = NetworkInterface.getNetworkInterfaces();
while (netInterfaces.hasMoreElements()) {
NetworkInterface ni = netInterfaces.nextElement();
System.out.println("DisplayName:" + ni.getDisplayName());
System.out.println("Name:" + ni.getName());
EnumerationInetAddress ips = ni.getInetAddresses();
while (ips.hasMoreElements()) {
System.out.println("IP:"
+ ips.nextElement().getHostAddress());
}
}
} catch (Exception e) {
e.printStackTrace();
}
*/
5.点对点通信
/*
import java.io.*;
import java.net.*;
*/
public class %%6 extends Thread {
@Override
public void run() {
ServerSocket server = null;
try {
server = new ServerSocket(5000);
} catch (Exception e) {
System.out.println("不能监听:" + e.toString());
}
Socket socket = null;
try {
socket = server.accept();
BufferedReader req = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
PrintWriter os = new PrintWriter(socket.getOutputStream());
Debug.p(req.readLine());
os.println("Server");
os.flush();
os.close();
req.close();
} catch (IOException e) {
System.out.println("出错:" + e.toString());
} finally {
try {
if (socket != null) {
socket.close();
server.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Thread t = new %%6();
t.start();
String strIP = null;
try {
strIP = InetAddress.getLocalHost().getHostAddress().toString();
} catch (UnknownHostException e) {
e.printStackTrace();
}
Socket socket = null;
try {
socket = new Socket(strIP, 4000);
PrintWriter pw = new PrintWriter(socket.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
pw.println("Client");
pw.flush();
Debug.p(br.readLine());
pw.close();
br.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}