【ClientSocketDemo.java 客戶端Java源代碼】
十年的寶清網站建設經驗,針對設計、前端、開發(fā)、售后、文案、推廣等六對一服務,響應快,48小時及時工作處理。網絡營銷推廣的優(yōu)勢是能夠根據(jù)用戶設備顯示端的尺寸不同,自動調整寶清建站的顯示方式,使網站能夠適用不同顯示終端,在瀏覽器中調整網站的寬度,無論在任何一種瀏覽器上瀏覽網站,都能展現(xiàn)優(yōu)雅布局與設計,從而大程度地提升瀏覽體驗。創(chuàng)新互聯(lián)建站從事“寶清網站設計”,“寶清網站推廣”以來,每個客戶項目都認真落實執(zhí)行。
import java.net.*;
import java.io.*;
public class ClientSocketDemo
{
//聲明客戶端Socket對象socket
Socket socket = null;
//聲明客戶器端數(shù)據(jù)輸入輸出流
DataInputStream in;
DataOutputStream out;
//聲明字符串數(shù)組對象response,用于存儲從服務器接收到的信息
String response[];
//執(zhí)行過程中,沒有參數(shù)時的構造方法,本地服務器在本地,取默認端口10745
public ClientSocketDemo()
{
try
{
//創(chuàng)建客戶端socket,服務器地址取本地,端口號為10745
socket = new Socket("localhost",10745);
//創(chuàng)建客戶端數(shù)據(jù)輸入輸出流,用于對服務器端發(fā)送或接收數(shù)據(jù)
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
//獲取客戶端地址及端口號
String ip = String.valueOf(socket.getLocalAddress());
String port = String.valueOf(socket.getLocalPort());
//向服務器發(fā)送數(shù)據(jù)
out.writeUTF("Hello Server.This connection is from client.");
out.writeUTF(ip);
out.writeUTF(port);
//從服務器接收數(shù)據(jù)
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();}
}
//執(zhí)行過程中,有一個參數(shù)時的構造方法,參數(shù)指定服務器地址,取默認端口10745
public ClientSocketDemo(String hostname)
{
try
{
//創(chuàng)建客戶端socket,hostname參數(shù)指定服務器地址,端口號為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();}
}
//執(zhí)行過程中,有兩個個參數(shù)時的構造方法,第一個參數(shù)hostname指定服務器地址
//第一個參數(shù)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;
//聲明并初始化服務器端監(jiān)聽端口號常量
public static final int PORT = 10745;
//聲明服務器端數(shù)據(jù)輸入輸出流
DataInputStream in;
DataOutputStream out;
//聲明InetAddress類對象ip,用于獲取服務器地址及端口號等信息
InetAddress ip = null;
//聲明字符串數(shù)組對象request,用于存儲從客戶端發(fā)送來的信息
String request[];
public ServerSocketDemo()
{
request = new String[3]; //初始化字符串數(shù)組
try
{
//獲取本地服務器地址信息
ip = InetAddress.getLocalHost();
//以PORT為服務端口號,創(chuàng)建serverSocket對象以監(jiān)聽該端口上的連接
serverSocket = new ServerSocket(PORT);
//創(chuàng)建Socket類的對象socket,用于保存連接到服務器的客戶端socket對象
Socket socket = serverSocket.accept();
System.out.println("This is server:"+String.valueOf(ip)+PORT);
//創(chuàng)建服務器端數(shù)據(jù)輸入輸出流,用于對客戶端接收或發(fā)送數(shù)據(jù)
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
//接收客戶端發(fā)送來的數(shù)據(jù)信息,并顯示
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]);
//向客戶端發(fā)送數(shù)據(jù)
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();
}
}
/**
* 基于UDP協(xié)議的聊天程序
*
* 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";
//發(fā)送端口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); //填寫發(fā)送消息
JLabel lblIP = new JLabel("IP地址:");
JLabel lblMSG = new JLabel("消息:");
JButton btnSend = new JButton("發(fā)送");
byte [] buf;
//定義DatagramSocket的對象必須進行異常處理
//發(fā)送和接收數(shù)據(jù)報包的套接字
DatagramSocket ds = null;
//=============構造函數(shù)=====================
public Chat()
{
CreateInterFace();
//注冊消息框監(jiān)聽器
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];
//表示接受數(shù)據(jù)報包
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對象//關閉數(shù)據(jù)報套接字
}
}
});
}
//界面設計布局
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函數(shù)===============================
public static void main(String[]args)
{
new Chat();
}
//================================發(fā)送消息===============================
//消息框回車發(fā)送消息事件
public void actionPerformed(ActionEvent e)
{
//得到文本內容
buf = txtMSG.getText().getBytes();
//判斷消息框是否為空
if (txtMSG.getText().length()==0)
{
JOptionPane.showMessageDialog(null,"發(fā)送消息不能為空","提示",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("");//清空消息框
//點發(fā)送按鈕發(fā)送消息事件
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();
}
}
}
CS模式的QQ這是服務器:ChatServer.javaimport java.net.*;
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("發(fā)布信息:"+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("出現(xiàn)問題:"+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個文件,先運行服務段端。。。 這是我以前學的時候寫過的!希望能幫的上你
共四個java文件,源代碼如下:
import java.awt.*;
import java.net.*;
import java.awt.event.*;
import java.io.*;
import java.util.Hashtable;
public class ChatArea extends Panel implements ActionListener,Runnable
{
Socket socket=null;
DataInputStream in=null;
DataOutputStream out=null;
Thread threadMessage=null;
TextArea 談話顯示區(qū),私聊顯示區(qū)=null;
TextField 送出信息=null;
Button 確定,刷新談話區(qū),刷新私聊區(qū);
Label 提示條=null;
String name=null;
Hashtable listTable;
List listComponent=null;
Choice privateChatList;
int width,height;
public ChatArea(String name,Hashtable listTable,int width,int height)
{
setLayout(null);
setBackground(Color.orange);
this.width=width;
this.height=height;
setSize(width,height);
this.listTable=listTable;
this.name=name;
threadMessage=new Thread(this);
談話顯示區(qū)=new TextArea(10,10);
私聊顯示區(qū)=new TextArea(10,10);
確定=new Button("送出信息到:");
刷新談話區(qū)=new Button("刷新談話區(qū)");
刷新私聊區(qū)=new Button("刷新私聊區(qū)");
提示條=new Label("雙擊聊天者可私聊",Label.CENTER);
送出信息=new TextField(28);
確定.addActionListener(this);
送出信息.addActionListener(this);
刷新談話區(qū).addActionListener(this);
刷新私聊區(qū).addActionListener(this);
listComponent=new List();
listComponent.addActionListener(this);
privateChatList=new Choice();
privateChatList.add("大家(*)");
privateChatList.select(0);
add(談話顯示區(qū));
談話顯示區(qū).setBounds(10,10,(width-120)/2,(height-120));
add(私聊顯示區(qū));
私聊顯示區(qū).setBounds(10+(width-120)/2,10,(width-120)/2,(height-120));
add(listComponent);
listComponent.setBounds(10+(width-120),10,100,(height-160));
add(提示條);
提示條.setBounds(10+(width-120),10+(height-160),110,40);
Panel pSouth=new Panel();
pSouth.add(送出信息);
pSouth.add(確定);
pSouth.add(privateChatList);
pSouth.add(刷新談話區(qū));
pSouth.add(刷新私聊區(qū));
add(pSouth);
pSouth.setBounds(10,20+(height-120),width-20,60);
}
public void setName(String s)
{
name=s;
}
public void setSocketConnection(Socket socket,DataInputStream in,DataOutputStream out)
{
this.socket=socket;
this.in=in;
this.out=out;
try
{
threadMessage.start();
}
catch(Exception e)
{
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==確定||e.getSource()==送出信息)
{
String message="";
String people=privateChatList.getSelectedItem();
people=people.substring(0,people.indexOf("("));
message=送出信息.getText();
if(message.length()0)
{
try {
if(people.equals("大家"))
{
out.writeUTF("公共聊天內容:"+name+"說:"+message);
}
else
{
out.writeUTF("私人聊天內容:"+name+"悄悄地說:"+message+"#"+people);
}
}
catch(IOException event)
{
}
}
}
else if(e.getSource()==listComponent)
{
privateChatList.insert(listComponent.getSelectedItem(),0);
privateChatList.repaint();
}
else if(e.getSource()==刷新談話區(qū))
{
談話顯示區(qū).setText(null);
}
else if(e.getSource()==刷新私聊區(qū))
{
私聊顯示區(qū).setText(null);
}
}
public void run()
{
while(true)
{
String s=null;
try
{
s=in.readUTF();
if(s.startsWith("聊天內容:"))
{
String content=s.substring(s.indexOf(":")+1);
談話顯示區(qū).append("\n"+content);
}
if(s.startsWith("私人聊天內容:"))
{
String content=s.substring(s.indexOf(":")+1);
私聊顯示區(qū).append("\n"+content);
}
else if(s.startsWith("聊天者:"))
{
String people=s.substring(s.indexOf(":")+1,s.indexOf("性別"));
String sex=s.substring(s.indexOf("性別")+2);
listTable.put(people,people+"("+sex+")");
listComponent.add((String)listTable.get(people));
listComponent.repaint();
}
else if(s.startsWith("用戶離線:"))
{
String awayPeopleName=s.substring(s.indexOf(":")+1);
listComponent.remove((String)listTable.get(awayPeopleName));
listComponent.repaint();
談話顯示區(qū).append("\n"+(String)listTable.get(awayPeopleName)+"離線");
listTable.remove(awayPeopleName);
}
Thread.sleep(5);
}
catch(IOException e)
{
listComponent.removeAll();
listComponent.repaint();
listTable.clear();
談話顯示區(qū).setText("和服務器的連接已中斷\n必須刷新瀏覽器才能再次聊天");
break;
}
catch(InterruptedException e)
{
}
}
}
}
ChatServer.java
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer
{
public static void main(String args[])
{
ServerSocket server=null;
Socket you=null;
Hashtable peopleList;
peopleList=new Hashtable();
while(true)
{
try
{
server=new ServerSocket(6666);
}
catch(IOException e1)
{
System.out.println("正在監(jiān)聽");
}
try {
you=server.accept();
InetAddress address=you.getInetAddress();
System.out.println("用戶的IP:"+address);
}
catch (IOException e)
{
}
if(you!=null)
{
Server_thread peopleThread=new Server_thread(you,peopleList);
peopleThread.start();
}
else {
continue;
}
}
}
}
class Server_thread extends Thread
{
String name=null,sex=null;
Socket socket=null;
File file=null;
DataOutputStream out=null;
DataInputStream in=null;
Hashtable peopleList=null;
Server_thread(Socket t,Hashtable list)
{
peopleList=list;
socket=t;
try {
in=new DataInputStream(socket.getInputStream());
out=new DataOutputStream(socket.getOutputStream());
}
catch (IOException e)
{
}
}
public void run()
{
while(true)
{ String s=null;
try
{
s=in.readUTF();
if(s.startsWith("姓名:"))
{
name=s.substring(s.indexOf(":")+1,s.indexOf("性別"));
sex=s.substring(s.lastIndexOf(":")+1);
boolean boo=peopleList.containsKey(name);
if(boo==false)
{
peopleList.put(name,this);
out.writeUTF("可以聊天:");
Enumeration enum=peopleList.elements();
while(enum.hasMoreElements())
{
Server_thread th=(Server_thread)enum.nextElement();
th.out.writeUTF("聊天者:"+name+"性別"+sex);
if(th!=this)
{
out.writeUTF("聊天者:"+th.name+"性別"+th.sex);
}
}
}
else
{
out.writeUTF("不可以聊天:");
}
}
else if(s.startsWith("公共聊天內容:"))
{
String message=s.substring(s.indexOf(":")+1);
Enumeration enum=peopleList.elements();
while(enum.hasMoreElements())
{
((Server_thread)enum.nextElement()).out.writeUTF("聊天內容:"+message);
}
}
else if(s.startsWith("用戶離開:"))
{
Enumeration enum=peopleList.elements();
while(enum.hasMoreElements())
{ try
{
Server_thread th=(Server_thread)enum.nextElement();
if(th!=thisth.isAlive())
{
th.out.writeUTF("用戶離線:"+name);
}
}
catch(IOException eee)
{
}
}
peopleList.remove(name);
socket.close();
System.out.println(name+"用戶離開了");
break;
}
else if(s.startsWith("私人聊天內容:"))
{
String 悄悄話=s.substring(s.indexOf(":")+1,s.indexOf("#"));
String toPeople=s.substring(s.indexOf("#")+1);
Server_thread toThread=(Server_thread)peopleList.get(toPeople);
if(toThread!=null)
{
toThread.out.writeUTF("私人聊天內容:"+悄悄話);
}
else
{
out.writeUTF("私人聊天內容:"+toPeople+"已經離線");
}
}
}
catch(IOException ee)
{
Enumeration enum=peopleList.elements();
while(enum.hasMoreElements())
{ try
{
Server_thread th=(Server_thread)enum.nextElement();
if(th!=thisth.isAlive())
{
th.out.writeUTF("用戶離線:"+name);
}
}
catch(IOException eee)
{
}
}
peopleList.remove(name);
try
{
socket.close();
}
catch(IOException eee)
{
}
System.out.println(name+"用戶離開了");
break;
}
}
}
}
import java.awt.*;
import java.io.*;
import java.net.*;
import java.applet.*;
import java.util.Hashtable;
ClientChat.java
public class ClientChat extends Applet implements Runnable
{
Socket socket=null;
DataInputStream in=null;
DataOutputStream out=null;
InputNameTextField 用戶提交昵稱界面=null;
ChatArea 用戶聊天界面=null;
Hashtable listTable;
Label 提示條;
Panel north, center;
Thread thread;
public void init()
{
int width=getSize().width;
int height=getSize().height;
listTable=new Hashtable();
setLayout(new BorderLayout());
用戶提交昵稱界面=new InputNameTextField(listTable);
int h=用戶提交昵稱界面.getSize().height;
用戶聊天界面=new ChatArea("",listTable,width,height-(h+5));
用戶聊天界面.setVisible(false);
提示條=new Label("正在連接到服務器,請稍等...",Label.CENTER);
提示條.setForeground(Color.red);
north=new Panel(new FlowLayout(FlowLayout.LEFT));
center=new Panel();
north.add(用戶提交昵稱界面);
north.add(提示條);
center.add(用戶聊天界面);
add(north,BorderLayout.NORTH);
add(center,BorderLayout.CENTER);
validate();
}
public void start()
{
if(socket!=nullin!=nullout!=null)
{ try
{
socket.close();
in.close();
out.close();
用戶聊天界面.setVisible(false);
}
catch(Exception ee)
{
}
}
try
{
socket = new Socket(this.getCodeBase().getHost(), 6666);
in=new DataInputStream(socket.getInputStream());
out=new DataOutputStream(socket.getOutputStream());
}
catch (IOException ee)
{
提示條.setText("連接失敗");
}
if(socket!=null)
{
InetAddress address=socket.getInetAddress();
提示條.setText("連接:"+address+"成功");
用戶提交昵稱界面.setSocketConnection(socket,in,out);
north.validate();
}
if(thread==null)
{
thread=new Thread(this);
thread.start();
}
}
public void stop()
{
try
{
socket.close();
thread=null;
}
catch(IOException e)
{
this.showStatus(e.toString());
}
}
public void run()
{
while(thread!=null)
{
if(用戶提交昵稱界面.get能否聊天()==true)
{
用戶聊天界面.setVisible(true);
用戶聊天界面.setName(用戶提交昵稱界面.getName());
用戶聊天界面.setSocketConnection(socket,in,out);
提示條.setText("祝聊天愉快!");
center.validate();
break;
}
try
{
Thread.sleep(100);
}
catch(Exception e)
{
}
}
}
}
InputNameTextField。java
import java.awt.*;
import java.net.*;
import java.awt.event.*;
import java.io.*;
import java.util.Hashtable;
public class InputNameTextField extends Panel implements ActionListener,Runnable
{
TextField nameFile=null;
String name=null;
Checkbox male=null,female=null;
CheckboxGroup group=null;
Button 進入聊天室=null,退出聊天室=null;
Socket socket=null;
DataInputStream in=null;
DataOutputStream out=null;
Thread thread=null;
boolean 能否聊天=false;
Hashtable listTable;
public InputNameTextField(Hashtable listTable)
{
this.listTable=listTable;
nameFile=new TextField(10);
group=new CheckboxGroup();
male=new Checkbox("男",true,group);
female=new Checkbox("女",false,group);
進入聊天室=new Button("進入");
退出聊天室=new Button("退出");
進入聊天室.addActionListener(this);
退出聊天室.addActionListener(this);
thread=new Thread(this);
add(new Label("昵稱:"));
add(nameFile);
add(male);
add(female);
add(進入聊天室);
add(退出聊天室);
退出聊天室.setEnabled(false);
}
public void set能否聊天(boolean b)
{
能否聊天=b;
}
public boolean get能否聊天()
{
return 能否聊天;
}
public String getName()
{
return name;
}
public void setName(String s)
{
name=s;
}
public void setSocketConnection(Socket socket,DataInputStream in,DataOutputStream out)
{
this.socket=socket;
this.in=in;
this.out=out;
try{
thread.start();
}
catch(Exception e)
{
nameFile.setText(""+e);
}
}
public Socket getSocket()
{
return socket;
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==進入聊天室)
{
退出聊天室.setEnabled(true);
if(能否聊天==true)
{
nameFile.setText("您正在聊天:"+name);
}
else
{
this.setName(nameFile.getText());
String sex=group.getSelectedCheckbox().getLabel();
if(socket!=nullname!=null)
{
try{
out.writeUTF("姓名:"+name+"性別:"+sex);
}
catch(IOException ee)
{
nameFile.setText("沒有連通服務器"+ee);
}
}
}
}
if(e.getSource()==退出聊天室)
{
try
{
out.writeUTF("用戶離開:");
}
catch(IOException ee)
{
}
}
}
public void run()
{
String message=null;
while(true)
{
if(in!=null)
{
try
{
message=in.readUTF();
}
catch(IOException e)
{
nameFile.setText("和服務器斷開"+e);
}
}
if(message.startsWith("可以聊天:"))
{
能否聊天=true;
break;
}
else if(message.startsWith("聊天者:"))
{
String people=message.substring(message.indexOf(":")+1);
listTable.put(people,people);
}
else if(message.startsWith("不可以聊天:"))
{
能否聊天=false;
nameFile.setText("該昵稱已被占用");
}
}
}
}
當前題目:java服務器聊天代碼 java聊天系統(tǒng)完整代碼
路徑分享:http://jinyejixie.com/article6/dodhsig.html
成都網站建設公司_創(chuàng)新互聯(lián),為您提供移動網站建設、網站內鏈、電子商務、小程序開發(fā)、虛擬主機、商城網站
聲明:本網站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)