真实的国产乱ⅩXXX66竹夫人,五月香六月婷婷激情综合,亚洲日本VA一区二区三区,亚洲精品一区二区三区麻豆

成都創(chuàng)新互聯(lián)網(wǎng)站制作重慶分公司

國產(chǎn)java服務器代碼的簡單介紹

JAVA聊天室 客戶端 和 服務器 完整代碼

CS模式的QQ這是服務器:ChatServer.javaimport java.net.*;

企業(yè)建站必須是能夠以充分展現(xiàn)企業(yè)形象為主要目的,是企業(yè)文化與產(chǎn)品對外擴展宣傳的重要窗口,一個合格的網(wǎng)站不僅僅能為公司帶來巨大的互聯(lián)網(wǎng)上的收集和信息發(fā)布平臺,成都創(chuàng)新互聯(lián)公司面向各種領域:成都酒店設計成都網(wǎng)站設計、成都營銷網(wǎng)站建設解決方案、網(wǎng)站設計等建站排名服務。


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("服務器已經(jīng)建立!");

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("聊天內(nèi)容"));

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個文件,先運行服務段端。。。 這是我以前學的時候?qū)戇^的!希望能幫的上你

有一個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服務器

我現(xiàn)寫了一個,可以訪問到靜態(tài)資源。你看情況多給點分吧

另外eclipse還沒有5.5,5.5的貌似是myEclipse吧

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

其中basePath指資源根路徑,默認是d:

可以通過命令行參數(shù)對其進行賦值

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();

}

}


網(wǎng)站題目:國產(chǎn)java服務器代碼的簡單介紹
文章鏈接:http://weahome.cn/article/doigdhs.html

其他資訊

在線咨詢

微信咨詢

電話咨詢

028-86922220(工作日)

18980820575(7×24)

提交需求

返回頂部