java网络编程应该怎样在客户端和服务器间实现通信?
以前写的,照贴了。。。服务器端:import java.awt.*;\x0d\x0aimport java.awt.event.WindowAdapter;\x0d\x0aimport java.awt.event.WindowEvent;\x0d\x0aimport java.io.*;\x0d\x0aimport java.net.*;/*6、 采用UDP协议,编写一个Java网络应用程序,该应用分服务器端程序和客户端程序两部分。\x0d\x0a* 客户端指定一个服务器上的文件名,让服务器发回该文件的内容,或者提示文件不存在。\x0d\x0a* (20分)(服务端程序和客户端程序分别命名为Server.java和Client.java)*/\x0d\x0apublic class N4BT6 extends Frame\x0d\x0a{\x0d\x0aDatagramSocket socket ;\x0d\x0aDatagramPacket packet ;byte[] buf ;\x0d\x0aFile file ;\x0d\x0aFileInputStream input;\x0d\x0aString message = "该文件不存在";\x0d\x0aTextArea text;\x0d\x0apublic N4BT6(String title)\x0d\x0a{\x0d\x0asuper(title);\x0d\x0atext = new TextArea(6,4);\x0d\x0aadd(text);\x0d\x0asetSize(400, 300);\x0d\x0asetVisible(true);\x0d\x0aaddWindowListener(new WindowAdapter()\x0d\x0a{\x0d\x0apublic void windowClosing(WindowEvent e)\x0d\x0a{\x0d\x0adispose();\x0d\x0a}\x0d\x0a});\x0d\x0a\x0d\x0abuf = new byte[1024];\x0d\x0atry\x0d\x0a{\x0d\x0asocket = new DatagramSocket(1230);\x0d\x0apacket = new DatagramPacket(buf, buf.length);\x0d\x0asocket.receive(packet);\x0d\x0afile = new File(new String(packet.getData()));\x0d\x0asocket = new DatagramSocket();\x0d\x0a} \x0d\x0acatch (Exception e)\x0d\x0a{e.printStackTrace();\x0d\x0a}\x0d\x0a\x0d\x0aif(file.exists())\x0d\x0a{\x0d\x0atry\x0d\x0a{\x0d\x0abuf = new byte[(int)file.length()];\x0d\x0apacket = new DatagramPacket(buf,buf.length,InetAddress.getLocalHost(),1234);\x0d\x0ainput = new FileInputStream(file);\x0d\x0ainput.read(buf);\x0d\x0asocket.send(packet);\x0d\x0a}\x0d\x0acatch (IOException e) \x0d\x0a{\x0d\x0ae.printStackTrace();\x0d\x0a}\x0d\x0a}\x0d\x0aelse\x0d\x0a{\x0d\x0atry\x0d\x0a{\x0d\x0apacket = new DatagramPacket(message.getBytes(),message.getBytes().length,\x0d\x0aInetAddress.getLocalHost(),1234);\x0d\x0asocket.send(packet);\x0d\x0a}\x0d\x0acatch (Exception e) \x0d\x0a{\x0d\x0ae.printStackTrace();\x0d\x0a}\x0d\x0a}\x0d\x0a\x0d\x0a}\x0d\x0apublic static void main(String[] args)\x0d\x0a{\x0d\x0anew N4BT6("Server");\x0d\x0a}\x0d\x0a}\x0d\x0a客户端:import java.awt.*;\x0d\x0aimport java.awt.event.*;\x0d\x0aimport java.net.DatagramPacket;\x0d\x0aimport java.net.DatagramSocket;\x0d\x0aimport java.net.InetAddress;public class N4BT6_2 extends Frame\x0d\x0a{\x0d\x0aTextArea text;\x0d\x0aString message = "Q.txt";\x0d\x0aDatagramSocket socket ;\x0d\x0aDatagramPacket packet;\x0d\x0abyte[] buf;\x0d\x0apublic N4BT6_2(String title)\x0d\x0a{\x0d\x0asuper(title);\x0d\x0atext = new TextArea(6,4);\x0d\x0aadd(text);\x0d\x0asetSize(400, 300);\x0d\x0asetVisible(true);\x0d\x0aaddWindowListener(new WindowAdapter()\x0d\x0a{\x0d\x0apublic void windowClosing(WindowEvent e)\x0d\x0a{\x0d\x0adispose();\x0d\x0a}\x0d\x0a});\x0d\x0atry\x0d\x0a{\x0d\x0a\x0d\x0asocket = new DatagramSocket();\x0d\x0apacket = new DatagramPacket(message.getBytes(),message.getBytes().length,\x0d\x0aInetAddress.getLocalHost(),1230);\x0d\x0asocket.send(packet);\x0d\x0a}\x0d\x0acatch (Exception e) \x0d\x0a{\x0d\x0ae.printStackTrace();\x0d\x0a}\x0d\x0a\x0d\x0atry\x0d\x0a{\x0d\x0abuf = new byte[1024];\x0d\x0asocket = new DatagramSocket(1234);\x0d\x0apacket = new DatagramPacket(buf,buf.length);\x0d\x0asocket.receive(packet);\x0d\x0atext.append(new String(buf));\x0d\x0a}\x0d\x0acatch (Exception e) \x0d\x0a{\x0d\x0ae.printStackTrace();\x0d\x0a}\x0d\x0a}\x0d\x0apublic static void main(String[] args)\x0d\x0a{\x0d\x0anew N4BT6_2("Client");\x0d\x0a}\x0d\x0a}
成都创新互联专业为企业提供盐边网站建设、盐边做网站、盐边网站设计、盐边网站制作等企业网站建设、网页设计与制作、盐边企业网站模板建站服务,10余年盐边做网站经验,不只是建网站,更提供有价值的思路和整体网络服务。
用java代码实现客户端与服务端建立连接?
套接字 Socket
import java.net.*;
Server:
ServerSocket server=new ServerSocket(port);//port是端口
Socket socket=server.accept();
//等待客户机的连接请求,若连接,则创建一套接字,并将返回。
Client:
Socket socket=new Socket("host",port);//host主机名(本机:127.0.0.1)
java,一台机器同时是客户端和服务器,服务器接收客户端信息并显示
假设你有a、b两台计算机,那么a可以向b发送文件,b也可以向a发送文件。所以在实现的时候,你的软件既要实现服务器的功能,也要实现客户端的功能。即:你的软件既可以申请发送文件,也可以在别人向你发送文件时接收文件。实现也不难,只是你判断用户需要的功能,然后根据功能实现相应的操作就行了。
java socket,我有客户端和服务器的代码,帮我添加广播和能多人会话,加分!!代码如下
根据你的改了个!不好意思,其中读写的思路稍微有点不同!不过可以做参考!
Server端代码:
import java.net.*;
import java.io.*;
import java.util.*;
public class TestServer {
ServerSocket s = null;
boolean started = false;//用来监听服务器是否启动!
ListServerReaderWriter clients = new ArrayListServerReaderWriter();//用来存放启动的客服端
public static void main(String[] args) {
new TestServer().start();
}
public void start() {
try {
s = new ServerSocket(5050);
started = true;
} catch(SocketException e) {
System.out.println("5050端口正在使用中!!!请关掉相关程序并重新运行服务器!");
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
}
int i = 1;
try {
while(started) {
Socket ss = s.accept();
ServerReaderWriter c = new ServerReaderWriter(ss);//建立客服端
System.out.println("第" + i + "个客服端启动!");
++i;
new Thread(c).start();//启动线程
clients.add(c);
}
} catch (EOFException e) {
System.out.println("客服端被关闭!");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ServerReaderWriter implements Runnable { //建议使用Runnable避免你重写run方法麻烦!
private Socket s;
private DataInputStream dis = null;//注意赋值,养成好习惯!
private DataOutputStream dos = null;
private boolean bConnected = false;//用于调用连接成功后的run方法
public ServerReaderWriter(Socket s) {
this.s = s;
try {
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
bConnected = true;
} catch (IOException e) {
e.printStackTrace();
}
}
public void send(String str) {
try {
dos.writeUTF(str);
} catch (IOException e) {
clients.remove(this);
System.out.println("有客户退出!");
}
}
public void run() {
try {
while (bConnected) {
String input = dis.readUTF();
System.out.println(input);
for(int i=0; iclients.size(); ++i) {
ServerReaderWriter c = clients.get(i);
c.send(input);
}
}
} catch(SocketException e) {
System.out.println("一个客服端已关闭,请勿再像他发送信息!");
} catch (EOFException e) {
System.out.println("谢谢使用!");
}catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (dis != null) {
dis.close();
}
if (dos != null) {
dos.close();
}
if (s != null) {
s.close();
s = null;
}
//clients.clear();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
Client端代码:
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
public class TestClient extends Frame { //用到Frame生产界面比较直观
Socket s = null;
DataOutputStream dos = null;
DataInputStream dis = null;
private boolean bConnected = false;
TextField tfText = new TextField();
TextArea taContent = new TextArea();
Thread tRecv = new Thread(new ClientReaderWriter());
public static void main(String[] args){
new TestClient().launchFrame();
}
public void launchFrame() {
this.setSize(300, 300); //设置客服端窗口格式
this.setLocation(400, 300);
add(tfText, BorderLayout.SOUTH);
add(taContent, BorderLayout.NORTH);
this.pack();
this.addWindowListener(new WindowAdapter() { //监听窗口关闭事件
public void windowClosing(WindowEvent arg0) {
disconnect();
System.exit(0);
}
});
tfText.addActionListener(new TFListener());
setVisible(true);
connect();
tRecv.start();
}
public void connect() {
try {
s = new Socket("127.0.0.1", 5050); //依据自己的服务器,我这里用的localhost
dos = new DataOutputStream(s.getOutputStream());
dis = new DataInputStream(s.getInputStream());
System.out.println("连接服务器!");
bConnected = true;
} catch(ConnectException e) {
System.out.println("请检查服务器是否启动!");
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.exit(0);
}
catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void disconnect() {
try {
dos.close();
dis.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private class TFListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String str = tfText.getText().trim();
tfText.setText("");
try {
dos.writeUTF(str);
if(str.equals("bye")){
System.exit(0);
}
dos.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
class ClientReaderWriter implements Runnable {
public void run() {
try {
while(bConnected) {
String input = dis.readUTF();
taContent.setText(taContent.getText() + input +'\n');
}
} catch (SocketException e) {
System.out.println("轻轻的我走了!Bye-bye!");
} catch (EOFException e) {
System.out.println("我断网了,再见!");
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
急求一段JAVA代码,有关客户端和服务器的。。。
客户端
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
/**
*
* @author Administrator
*/
public class Main extends JFrame{
JPanel jp;
JButton jb;
javax.swing.JTextField jt1;
JTextField jt2;
JTextField jt3;
JLabel jl1;
JLabel jl2;
public Main()
{
this.setBounds(150, 50, 300, 100);
jp= new JPanel(new GridLayout(3, 2));
jb=new JButton("登陆");
jt1=new JTextField();
jt2=new JTextField();
jt3=new JTextField();
jt3.setEditable(false);
jl1=new JLabel("用户名");
jl2=new JLabel("密码");
this.getContentPane().add(jp);
jp.add(jl1);
jp.add(jt1);
jp.add(jl2);
jp.add(jt2);
jp.add(jt3);
jp.add(jb);
this.setVisible(true);
jb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String sentence;
String modifiedSentence = null;
//BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = null;
try {
clientSocket = new Socket("127.0.0.1", 6789);
} catch (UnknownHostException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
//System.out.println("connection ok");
DataOutputStream outToServer = null;
try {
outToServer = new DataOutputStream(clientSocket.getOutputStream());
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
BufferedReader inFromServer = null;
try {
inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
sentence=jt1.getText()+" "+jt2.getText();
try {
//System.out.println(sentence);
outToServer.writeBytes(sentence + '\n');
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
try {
modifiedSentence = inFromServer.readLine();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
//System.out.println("FROM SERVER:"+modifiedSentence);
jt3.setText(modifiedSentence);
try {
clientSocket.close();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws Exception
{
Main m=new Main();
}
}
服务器端
import java.io.*;
import java.net.*;
public class Main {
public static void main(String[] args) throws Exception {
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket=new ServerSocket(6789);
while(true){
Socket connectionSocket=welcomeSocket.accept();
BufferedReader inFromClient=new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient=new DataOutputStream(connectionSocket.getOutputStream());
clientSentence=inFromClient.readLine();
//capitalizedSentence=clientSentence.toUpperCase()+'\r'+'\n';
//outToClient.writeBytes(capitalizedSentence);
if(clientSentence.equalsIgnoreCase("admin 1234"))
outToClient.writeBytes("ok"+'\n');
else
outToClient.writeBytes("error"+'\n');
}
}
}
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客户端和服务端代码 java服务器端
网页地址:http://lswzjz.com/article/hicscc.html