导航:首页 > 编程语言 > java网络编程例子

java网络编程例子

发布时间:2023-04-17 03:21:54

❶ 一个最简单的java网络编程

你好:Socket s = new Socket("localhost", 6660);//14行

这个的话,你的没通, 去黑窗口输入 tenlet 127.0.0.1 6660;看看是否有结果输出,再就是你别用localhost了,换成实际的127.0.0.1的地址,

❷ java Socket网络编程

调用 outt.flush ();

❸ 求java nio网络编程的小例子,要求客户端一直与服务器保持连接

import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.net.*;
import java.io.*;

public class chatClient extends Frame {

/**
* @param args
*/
TextField tfTxT=new TextField();
TextArea taContent=new TextArea();
Socket s=null;
DataOutputStream dos=null;
DataInputStream dis=null;
private boolean bConnected =false;

public static void main(String[] args) {
new chatClient().lunachFrame();
}

private class RecvThread implements Runnable{

public void run() {
try{
while(bConnected){
String str=dis.readUTF();
taContent.setText(taContent.getText()+str+'\n');
}
}catch(IOException e){
e.printStackTrace();
}
}

}

public void lunachFrame(){
this.setLocation(400, 300);
this.setSize(300,300);
//this.setLayout(new FlowLayout());
this.add(tfTxT,"South");
this.add(taContent,"North");
pack();
tfTxT.addActionListener(new TFListener());
this.addWindowListener(new WindowClose());
this.setVisible(true);
connect();
new Thread(new RecvThread()).start();
}

public void connect(){
try {
s= new Socket("127.0.0.1",8888);
dos =new DataOutputStream(s.getOutputStream());
dis =new DataInputStream(s.getInputStream());
System.out.println("connected!");
bConnected=true;
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

public void disconnect(){
try {
dos.close();
s.close();
} catch (Exception e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
}

class WindowClose extends WindowAdapter{

@Override
public void windowClosing(WindowEvent e) {
// TODO 自动生成方法存根
System.exit(0);
disconnect();
}

}

private class TFListener implements ActionListener{

public void actionPerformed(ActionEvent e) {
String str=tfTxT.getText().trim();//trim去掉两边空格
//taContent.setText(str);
tfTxT.setText("");
try {
dos.writeUTF(str);
dos.flush();
//dos.close();

} catch (IOException e1) {
e1.printStackTrace();

}
}
}
}

======================================
import java.io.IOException;
import java.net.*;
import java.io.*;
import java.util.*;

public class ChatServer {
List<Client> clients=new ArrayList<Client>();
Client c=null;

public static void main(String[] args){
new ChatServer().start();
}

public void start(){
boolean started=false;
ServerSocket ss=null;
DataInputStream dis=null;
try{
ss=new ServerSocket(8888);
started =true;
}catch(Exception e)
{
e.printStackTrace();
}
try{
while(started){
Socket s=ss.accept();
c=new Client(s);//启动线程,实行run()方法
System.out.println("a client connected!");
new Thread(c).start();//启动start方法,循环.start是Thread中的方法与这上面的start无关
clients.add(c);
//dis.close();
}
} catch (Exception e) {

//e.printStackTrace();
}
finally{
try {
ss.close();
} catch (IOException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
}
}

class Client implements Runnable{

private Socket s;
private DataInputStream dis =null;
private boolean bConnected =false;
private DataOutputStream dos=null;

public Client(Socket s){
this.s=s;
try {
dis=new DataInputStream(s.getInputStream());
dos =new DataOutputStream(s.getOutputStream());
bConnected =true;
} catch (IOException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
}

public void send(String str)throws Exception{
dos.writeUTF(str);

}

public void run() {
try{
while(bConnected){
String str = dis.readUTF();
System.out.println(str);
for(int i=0;i<clients.size();i++){
c=clients.get(i);
c.send(str);
}
/*for(Iterator<Client> it=clients.iterator();it.hasNext();){
Client c=it.next();
c.send(str);
}*/
}
}catch(SocketException e){
clients.remove(this);
System.out.println("客户下线了");
}
catch(EOFException e){
System.out.println("Client closed");
}
catch (Exception e){

//e.printStackTrace();
}
finally{
try {
if(dis !=null) dis.close();
if(dos !=null) dos.close();
if(s!=null) s.close();
} catch (Exception e1) {
// TODO 自动生成 catch 块
//e1.printStackTrace();
}
}
}
}

}

第一个是客户端,
第二个是server端

❹ 求一个用JAVA写的网络编程的网络聊天系统,能够实现两个人聊天信息收发。

这个是客户端
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
public class client extends Frame implements ActionListener{
int i=1;Frame f;
TextField ip,port;
Label Lip,Lport;
Button connect,exit;
public static void main(String args[])
{client c1 = new client();
c1.init();
}
public void init()
{
f=new Frame("client connection");
f.setLayout(new FlowLayout());
ip =new TextField("localhost");
port =new TextField("8189",5);
Lip=new Label("ip address");
Lport=new Label("port");
connect=new Button("connect");
exit=new Button("exit");
connect.addActionListener(this);
exit.addActionListener(this);
f.add(Lip);
f.add(ip);
f.add(Lport);
f.add(port);
f.add(connect);
f.add(exit);
f.setSize(500,60);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==exit)
System.exit(0);
if(e.getSource()==connect)
{
new Thread(new threadclient(ip.getText(),port.getText(),i)).start();
i++;
}
}
}
class threadclient extends Frame implements Runnable,ActionListener{
String ip,port;
int no;
Frame f;
TextArea ta;
TextArea name;
TextField tf;
Button send,bye;
InputStream ins;
Socket s;
PrintStream out1;
BufferedReader in;
BufferedWriter out;
threadclient(String n,String m,int i)
{
ip=n;
port=m;
no=i;
}
public void run(){
f=new Frame("client NO." +no);
f.setLayout(new FlowLayout());
ta=new TextArea("",10,30,TextArea.SCROLLBARS_BOTH);
tf=new TextField("",20);
send=new Button("send");
bye=new Button("bye");
send.addActionListener(this);
bye.addActionListener(this);
f.add(ta);
f.add(tf);
f.add(send);
f.add(bye);
f.setSize(300,300);
f.setVisible(true);
Integer tmp=new Integer(port);
int portint =tmp.intValue();
try
{
s=new Socket(ip,portint);
in=new BufferedReader(new InputStreamReader(s.getInputStream()));
out1=new PrintStream(s.getOutputStream());
ta.append(in.readLine()+"\n");
}catch(Exception e)
{
System.out.println(e.getMessage()+" ss");
}
}
public void send(String txt){
try{
out1.println(txt);
out1.flush();
ta.append(in.readLine()+"\n");
}catch(IOException e)
{
System.out.println(e.getMessage()+"send");
}
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==bye){
send("BYE");
System.exit(0);
}
if (e.getSource()==send)
send(tf.getText());
}
}

这个是服务器
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
public class server {
private static Map<String,Socket> clientMap=new HashMap<String,Socket>();
public static void main(String[] args) {
int i = 1;
try {
ServerSocket s = new ServerSocket(8189);
for (;;) {
Socket incoming = s.accept();
System.out.println("连接成功" + i);
ThreadedEchoHandler teh=new ThreadedEchoHandler(incoming, i);
teh.start();
String name=teh.getClientname();
clientMap.put(name,incoming);
i++;
}
} catch (Exception e) {
System.out.println(e);
}
}
}
class ThreadedEchoHandler extends Thread {
Frame f;
TextArea ta;
TextField tf;
Button send, bye;
InputStream ins;
Socket s;
PrintStream out1;
BufferedReader in;
PrintWriter out;
public ThreadedEchoHandler(Socket i, int c) {
incoming = i;
counter = c;
f=new Frame("server");
f.setLayout(new FlowLayout());
ta=new TextArea("",10,30,TextArea.SCROLLBARS_BOTH);
tf=new TextField("",20);
send=new Button("send");
bye=new Button("bye");
send.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
send(tf.getText());

}

});
bye.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
send("bye");

}

});
f.add(ta);
f.add(tf);
f.add(send);
f.add(bye);
f.setSize(300,300);
f.setVisible(true);
}

public String getClientname() {
try {
in = new BufferedReader(new InputStreamReader(
incoming.getInputStream()));
out = new PrintWriter(incoming.getOutputStream(), true);
return in.readLine();
} catch (IOException e) {
System.out.println(e.getMessage()+"get");
}
return null;
}
public void send(String context){
out.println(context);
out.flush();
}
public void run() {
try {

boolean done = false;
while (!done) {
String str = in.readLine();

if (str == null)
done = true;
else {
out.println("Echo(" + counter + "):" + str);
ta.append("Echo(" + counter + "):" + str+"\n");
if (str.trim().equals("BYE"))
done = true;
}
}
incoming.close();
} catch (Exception e) {
System.out.println(e.getMessage()+"run");
}
}
private Socket incoming;
private int counter;
}

这个鸟东西是个新手写的。唉,太烂了,我无力吐槽。

❺ 我要一份用java网络编程写的点对点的两人聊天程序(TCP和UDP)

Server端:
import java.io.*;
import java.net.*;
import java.applet.Applet;
public class TalkServer{
public static void main(String args[]) {
try{
ServerSocket server=null;
try{
server=new ServerSocket(4700);
}catch(Exception e) {
System.out.println("can not listen to:"+e);
}
Socket socket=null;
try{
socket=server.accept();
}catch(Exception e) {
System.out.println("Error."+e);
}
String line;
BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter os=new PrintWriter(socket.getOutputStream());
BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Client:"+is.readLine());
line=sin.readLine();
while(!line.equals("bye")){
os.println(line);
os.flush();
System.out.println("Server:"+line);
System.out.println("Client:"+is.readLine());
line=sin.readLine();
}
os.close();
is.close();
socket.close();
server.close();
}catch(Exception e){
System.out.println("Error:"+e);
}
}
}

Client端:
import java.io.*;
import java.net.*;
public class TalkClient {
public static void main(String args[]) {
try{
Socket socket=new Socket("127.0.0.1",4700);
BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));
PrintWriter os=new PrintWriter(socket.getOutputStream());
BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream()));
String readline;
readline=sin.readLine(); //从系统标准输入读入一字符串
while(!readline.equals("bye")){
os.println(readline);
os.flush();
System.out.println("Client:"+readline);
System.out.println("Server:"+is.readLine());
readline=sin.readLine(); //从系统标准输入读入一字符串
}
os.close(); //关闭Socket输出流
is.close(); //关闭Socket输入流
socket.close(); //关闭Socket
}catch(Exception e) {
System.out.println("Error"+e); //出错,则打印出错信息
}
}
}

阅读全文

与java网络编程例子相关的资料

热点内容
基于单片机饮水机温度控制系统的设计 浏览:455
c中委托被编译后的结构 浏览:152
飞燕app怎么注销账号 浏览:895
cad命令缩小 浏览:154
linux发展史 浏览:629
服务器选用什么CPU比较好 浏览:334
明星怎么宣传安卓 浏览:953
8255芯片编程 浏览:65
java文件bat运行 浏览:747
java常见笔试 浏览:529
360程序员模式 浏览:363
AQS算法的查询树构造 浏览:329
小猪微信营销源码 浏览:12
阿里云服务器能连接打印机吗 浏览:175
命令行参考 浏览:281
怎么初步认识编程 浏览:208
为什么程序员都喜欢谷歌 浏览:891
压缩性骨拆能自愈吗 浏览:277
安卓怎么设置游戏画面 浏览:114
k线上写字源码 浏览:457