RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
国产java服务器代码的简单介绍

JAVA聊天室 客户端 和 服务器 完整代码

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("发布信息:"+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个文件,先运行服务段端。。。 这是我以前学的时候写过的!希望能帮的上你

有一个java写的服务器代码,在eclipse怎么让它运行起来?这个软件完全不会用啊

这样:

打开eclipse,点击file -- new -- java project会弹出一窗口,project name 文本框里填上 test,--- 点击finsh --然后点击左边刚建立的test----new --- class ---会弹出一个窗口---name文本框里填上: ChatServer --- finsh ---然后会生成一个类,你把右边对话框里刚生成的public class ChatServer {

}

这些代码删掉,然后把你的那些代码粘贴到那对话框中,然后你将鼠标放在该对话框中右击,--》 Run AS ---- java application

这样应该没问题了

Java Web服务器

我现写了一个,可以访问到静态资源。你看情况多给点分吧

另外eclipse还没有5.5,5.5的貌似是myEclipse吧

其中port指端口,默认是地址是

其中basePath指资源根路径,默认是d:

可以通过命令行参数对其进行赋值

import java.io.BufferedReader;

import java.io.ByteArrayOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.OutputStream;

import java.io.PrintStream;

import java.net.ServerSocket;

import java.net.Socket;

import java.net.URLDecoder;

public class SimpleHttpServer {

private static int port = 8088;

private static String basePath = "D:/";

public static void main(String[] args) {

if (args.length = 1) {

basePath = args[0];

}

if (args.length = 2) {

port = Integer.parseInt(args[1]);

}

System.out.println("server starting:");

System.out.println("base path:" + basePath);

System.out.println("Listening at:" + port);

startServer();

System.out.println("server started succesfully");

}

private static void startServer() {

new Thread() {

public void run() {

try {

ServerSocket ss = new ServerSocket(port);

while (true) {

final Socket s = ss.accept();

new Thread() {

public void run() {

try {

OutputStream socketOs = s.getOutputStream();

BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));

String line;

String headerLine = null;

while ((line = br.readLine()) != null) {

if (headerLine == null) {

headerLine = line;

}

if ("".equals(line)) {

break;

}

}

String target = headerLine.replaceAll("^.+ (.+) HTTP/.+$", "$1");

String queryString;

String[] tmp = target.split("\\?");

target = URLDecoder.decode(tmp[0], "utf-8");

target = target.endsWith("/") ? target.substring(0, target.length() - 1) : target;

if (tmp.length 1) {

queryString = tmp[1];

} else {

queryString = "";

}

String filePath = basePath + target;

File f = new File(filePath);

if (!f.exists()) {

StringBuffer content = new StringBuffer();

content.append("htmlheadtitleResource Not Found/title/headbodyh1The requested resource ")

.append(target).append(" is not found./h1/body/html");

StringBuffer toWrite = new StringBuffer();

toWrite.append("HTTP/1.1 404 Not Found\r\nContent-Length:").append("" + content.length()).append("\r\n\r\n")

.append(content);

socketOs.write(toWrite.toString().getBytes());

} else if (f.isDirectory()) {

StringBuffer content = new StringBuffer();

content.append("htmlheadtitle").append(target).append(

"/title/headbodytable border='1' width='100%'");

content.append("trth align='left' width='40px'").append("Path").append("/thtd").append(target.length()0?target:"/")

.append("/td/tr");

content.append("trth align='left'Type/thth align='left'Name/th/tr");

if (!basePath.equals(filePath)) {

content.append("trtdDirectory/tdtd").append("a href='").append(

target.substring(0, target.lastIndexOf("/") + 1)).append("'../a").append("/td/tr");

}

File[] files = f.listFiles();

for (File file : files) {

content.append("trtd");

if (file.isFile()) {

content.append("File/tdtd");

} else if (file.isDirectory()) {

content.append("Directory/tdtd");

}

content.append("a href=\"").append(target);

if (!(target.endsWith("/") || target.endsWith("\\"))) {

content.append("/");

}

content.append(file.getName()).append("\"").append(file.getName()).append("/a/td/tr");

}

content.append("/table/body/html");

StringBuffer sb = new StringBuffer();

sb.append("HTTP/1.1 200 OK\r\nCache-Control: max-age-0\r\n");

sb.append("Content-Length:").append("" + content.length()).append("\r\n\r\n");

sb.append(content);

socketOs.write(sb.toString().getBytes());

} else if (f.isFile()) {

socketOs.write(("HTTP/1.1 200 OK\r\nCache-Control: max-age-0\r\nContent-Length:" + f.length() + "\r\n\r\n")

.getBytes());

byte[] buffer = new byte[1024];

FileInputStream fis = new FileInputStream(f);

int cnt = 0;

while ((cnt = fis.read(buffer)) = 0) {

socketOs.write(buffer, 0, cnt);

}

fis.close();

}

socketOs.close();

} catch (Exception e) {

try {

s.getOutputStream().write("HTTP/1.1 500 Error\r\n".getBytes());

ByteArrayOutputStream byteos = new ByteArrayOutputStream();

PrintStream printStream = new PrintStream(byteos);

printStream

.write("htmlheadtitleError 500/title/headbodyh1Error 500/h1pre style='font-size:15'"

.getBytes());

e.printStackTrace(printStream);

printStream.write("/prebody/html".getBytes());

byteos.close();

byte[] byteArray = byteos.toByteArray();

s.getOutputStream().write(("Content-Length:" + byteArray.length + "\r\n\r\n").getBytes());

s.getOutputStream().write(byteArray);

s.close();

} catch (IOException e1) {

e1.printStackTrace();

}

}

}

}.start();

}

} catch (Exception e) {

e.printStackTrace();

}

}

}.start();

}

}


分享文章:国产java服务器代码的简单介绍
网站地址:http://lswzjz.com/article/doigdhs.html