導航:首頁 > 編程語言 > socketjava源代碼

socketjava源代碼

發布時間:2025-06-11 21:27:39

1. java socket網路編程

//==============Server.java=================//
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
public static void main(String[] args) throws IOException {
ServerSocket s = new ServerSocket(12345);
System.out.println("伺服器就緒,請啟動客戶端.");
Socket so = s.accept();
byte[] buff = new byte[1024];
int read = so.getInputStream().read(buff);
String[] abc=new String(buff,0,read).split("\\D+");
int a = Integer.parseInt(abc[0]);
int b = Integer.parseInt(abc[1]);
int c = Integer.parseInt(abc[2]);
if(!cbt(a,b,c))
so.getOutputStream().write("輸入的數據無法組成三角形.".getBytes());
else
so.getOutputStream().write(getArea(a,b,c).getBytes());
so.getOutputStream().flush();
so.close();
s.close();
}

private static String getArea(int a, int b, int c) {
float s = (a+b+c)/2f;
return "面積: "+Math.sqrt(s*(s-a)*(s-b)*(s-c));
}

private static boolean cbt(int a, int b, int c) {
return a>0&&b>0&&c>0&&a+b>c&&b+c>a&&a+c>b;
}
}

//=================Client.java======================//
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException {
System.out.println("輸入三角形的三邊並用逗號隔開,如: (3,4,5) ");
byte[] buff=new byte[64];
int r = System.in.read(buff);
String ipaddr = "localhost";//根據情況改變,在本機調試就不改了
Socket so = new Socket(ipaddr,12345);
so.getOutputStream().write(new String(buff,0,r).getBytes());
r = so.getInputStream().read(buff);
so.close();
String rs = new String(buff,0,r);
System.out.println(rs);
}

}

//先啟動Server,再啟動Client

2. Java TCP socket通信,如何實現發送十六進制值,並在數據接收窗口中顯示這些數據對應的字元串,非常感謝!

我自己的電腦上有一段源代碼,就是基於TCP聊天小代碼,能進行相互之間的消息接受。我的代碼是直接傳輸字元串的,不是16進制滴。嗯,也貼出來看看吧!

運行伺服器,c1,c2就可以了,c1與c2可進行通信。

Client.java

import java.net.*;
public class Client{
static byte num=1;
private int portNum;

public Client(int portnum){
this.portNum=portnum;
System.out.println("您是第"+num+"位客服端");
num++;
}

public void sentMessage(String me){
//都是向伺服器發信息埠號1999
try{
DatagramSocket ds=new DatagramSocket();
DatagramPacket dp=new DatagramPacket(me.getBytes(),me.length(),InetAddress.getByName("127.0.0.1"),1999);
ds.send(dp);
ds.close();
}catch(Exception e){
e.printStackTrace();
}

}

public String receiveMessage(){
String str="";
try{
DatagramSocket ds=new DatagramSocket(this.portNum);//表示哦自己的接收埠號是1999
byte[] buf=new byte[1024];
DatagramPacket dp=new DatagramPacket(buf,1024);
ds.receive(dp);
str=new String(dp.getData(),0,dp.getLength());
ds.close();
}catch(Exception e){
e.printStackTrace();
}

return str;
}
}

c1.java

import java.util.*;
public class c1 implements Runnable{
Client cl;
boolean goon=true;
Scanner sc=new Scanner(System.in);
public c1(){
cl=new Client(2000);
System.out.println("這里是2000客戶端\n你可以發送信息。請輸入要發送的信息。out退出");

new Thread(this).start();
while(this.goon==true){
say();
}
if(goon==false){
System.exit(0);
}
}

public static void main(String[] args){
new c1();
}

public void say(){
String mess=sc.nextLine();
System.out.println("是否發送y/n");
String key=sc.nextLine();
if(key.equals("y")){
System.out.println("信息信息發送中……");
try{
cl.sentMessage(mess);
}catch(Exception e){
e.printStackTrace();
}
}
else if(key.equals("out")){
goon=false;
}
}

public void run(){
while(this.goon==true){
String sst="";
try{
sst=cl.receiveMessage();
}catch(Exception e){
e.printStackTrace();
}

if(sst.length()>0){
System.out.println(sst);
}
try{
Thread.sleep(100);
}catch(InterruptedException e){
e.printStackTrace();
}

}
System.out.println("程序結束!");
}
}

c2.java

import java.util.*;
public class c2 implements Runnable{
Client cl;
boolean goon=true;
Scanner sc=new Scanner(System.in);
public c2(){
cl=new Client(2001);
System.out.println("這里是2001客戶端\n你可以發送信息。請輸入要發送的信息。out退出");
new Thread(this).start();
while(goon==true){
say();
}
if(goon==false){
System.exit(0);
}
}

public static void main(String[] args){
new c2();
}

public void say(){
String mess=sc.nextLine();
System.out.println("是否發送y/n");
String key=sc.nextLine();
if(key.equals("y")){
System.out.println("信息信息發送中……");
try{
cl.sentMessage(mess);
}catch(Exception e){
e.printStackTrace();
}
}
else if(key.equals("out")){
this.goon=false;
}
}

public void run(){
while(this.goon==true){
String sst="";
try{
sst=cl.receiveMessage();
}catch(Exception e){
e.printStackTrace();
}

if(sst.length()>0){
System.out.println(sst);
}
try{
Thread.sleep(100);
}catch(InterruptedException e){
e.printStackTrace();
}

}
System.out.println("聊天關閉!");
}
}

Server.java

import java.net.*;
import java.util.*;
public class Server implements Runnable{
private String message;
boolean work=true;
byte tm=10;
String[] clomessage={"信息:正在斷開網路連接.",".",".\n","信息:設置保存中……","","","完成\n","信息:歡迎下次使用\n","信息:完成\n","Goodbye!"};
public Server(){
new Thread(this).start();
System.out.println("本程序為服務端Server");
Scanner sc=new Scanner(System.in);
System.out.println("輸入命令out關閉伺服器");
String clo=sc.nextLine();
if(clo.equals("out")){
System.out.println("正在關閉伺服器……");
setwork(false);
System.exit(0);
}

}

public static void main(String[] args){
new Server();

}

public void setwork(boolean bo)
{
this.work=bo;
}

public void setMessage(String str){
this.message=str;
}

public String getMessage(){
return this.message;
}

public void sentMessage(){
String mes=this.getMessage();
try{
DatagramSocket ds=new DatagramSocket();
DatagramPacket dp=new DatagramPacket(mes.getBytes(),mes.length(),InetAddress.getByName("127.0.0.1"),2000);
DatagramPacket dp2=new DatagramPacket(mes.getBytes(),mes.length(),InetAddress.getByName("127.0.0.1"),2001);
ds.send(dp);
ds.send(dp2);
ds.close();
System.out.println("信息發送至:127.0.0.1:2000 & 127.0.0.1:2001");
this.setMessage("");
}catch(Exception e){
e.printStackTrace();
}
}

public void receiveMessage() throws Exception{
try{
DatagramSocket ds=new DatagramSocket(1999);//表示哦自己的接收埠號是1999
byte[] buf=new byte[1024];
DatagramPacket dp=new DatagramPacket(buf,1024);
ds.receive(dp);
String str=new String(dp.getData(),0,dp.getLength());
if(str.length()>0){
this.setMessage(str);
System.out.println("信息:Server從"+dp.getAddress().getHostAddress()+"主機(埠號:"+dp.getPort()+")收到信息:"+this.getMessage());
}

ds.close();
}catch(Exception e){
e.printStackTrace();
}
}

public void run(){
while(tm>0){
if(work==false){
tm--;
System.out.print(clomessage[9-tm]);
}
try{
receiveMessage();//時刻接受信息
}catch(Exception e){
e.printStackTrace();
}

if(this.getMessage().length()>0){//如果接收到信息則發送信息

try{
sentMessage();
}catch(Exception e){
e.printStackTrace();
}
try{
Thread.sleep(100);
}catch(InterruptedException e){
e.printStackTrace();
}

}
}
}
}

呵呵,請指教啊!

3. java 聊天室 源代碼

最簡單的聊天室

4. java socket如果服務端掉線 客戶端應該怎樣重連,實現的思路是怎麼樣的,最好能有具體的代碼參考一下

看代碼,不明白的追問

// 無窮循環,用於自動重新連接網關
while (true) {
// 捕獲sleep異常
try {
// 捕獲socket異常
try {
// 創建socket連接
socketGateway = new Socket("127.0.0.1", 8888);

// 創建輸入輸出對象
inStream = new DataInputStream(socketGateway.getInputStream());
outStream = new DataOutputStream(socketGateway.getOutputStream());

byte buf[] = new byte[1]; // 數據緩沖區
int intLen; // 讀緩沖區返回的長度

// 無窮循環,用於讀緩沖區數據
while (true) {
// 捕獲讀緩沖區異常
try {
intLen = inStream.read(buf, 0, 1);

// 可讀長度-1則斷開連接
if (intLen == -1) {
break;
}

// 處理buf
}

// 連接斷開
catch (EOFException e) {
break;
}

// 接收數據超時
catch (SocketTimeoutException e) {
break;
}

// 超過數據包末尾
catch (IOException e) {
break;
}
}
} catch (Exception e) {
// 處理socket錯誤
}

// 休眠1秒後重連
sleep(1000);
} catch (Exception e) {
// 處理sleep錯誤
}
}

5. 怎麼用java的socket進行文件傳輸誰能給個簡單的例子,包括發送端和接收端。

java中的網路信息傳輸方式是基於TCP協議或者UD協議P的,socket是基於TCP協議的

例子1
(1)客戶端程序:
import java.io.*;
import java.net.*;
public class Client
{ public static void main(String args[])
{ String s=null;
Socket mysocket;
DataInputStream in=null;
DataOutputStream out=null;
try{
mysocket=new Socket("localhost",4331);
in=new DataInputStream(mysocket.getInputStream());
out=new DataOutputStream(mysocket.getOutputStream());
out.writeUTF("你好!");//通過 out向"線路"寫入信息。
while(true)
{
s=in.readUTF();//通過使用in讀取伺服器放入"線路"里的信息。堵塞狀態,
//除非讀取到信息。
out.writeUTF(":"+Math.random());
System.out.println("客戶收到:"+s);
Thread.sleep(500);
}
}
catch(IOException e)
{ System.out.println("無法連接");
}
catch(InterruptedException e){}
}
}
(2)伺服器端程序:
import java.io.*;import java.net.*;
public class Server
{ public static void main(String args[])
{ ServerSocket server=null;
Socket you=null;String s=null;
DataOutputStream out=null;DataInputStream in=null;
try{ server=new ServerSocket(4331);}
catch(IOException e1){System.out.println("ERRO:"+e1);}
try{ you=server.accept();
in=new DataInputStream(you.getInputStream());
out=new DataOutputStream(you.getOutputStream());
while(true)
{
s=in.readUTF();// 通過使用in讀取客戶放入"線路"里的信息。堵塞狀態,
//除非讀取到信息。

out.writeUTF("你好:我是伺服器");//通過 out向"線路"寫入信息.
out.writeUTF("你說的數是:"+s);
System.out.println("伺服器收到:"+s);
Thread.sleep(500);
}
}
catch(IOException e)
{ System.out.println(""+e);
}
catch(InterruptedException e){}
}
}

例子(2)
(1) 客戶端
import java.net.*;import java.io.*;
import java.awt.*;import java.awt.event.*;
import java.applet.*;
public class Computer_client extends Applet implements Runnable,ActionListener
{ Button 計算;TextField 輸入三邊長度文本框,計算結果文本框;
Socket socket=null;
DataInputStream in=null; DataOutputStream out=null;
Thread thread;
public void init()
{ setLayout(new GridLayout(2,2));
Panel p1=new Panel(),p2=new Panel();
計算=new Button(" 計算");
輸入三邊長度文本框=new TextField(12);計算結果文本框=new TextField(12);
p1.add(new Label("輸入三角形三邊的長度,用逗號或空格分隔:"));
p1.add( 輸入三邊長度文本框);
p2.add(new Label("計算結果:"));p2.add(計算結果文本框);p2.add(計算);
計算.addActionListener(this);
add(p1);add(p2);
}
public void start()
{ try
{ //和小程序所駐留的伺服器建立套接字連接:
socket = new Socket(this.getCodeBase().getHost(), 4331);
in =new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
}
catch (IOException e){}
if(thread == null)
{ thread = new Thread(this);
thread.start();
}
}
public void run()
{ String s=null;
while(true)
{ try{ s=in.readUTF();//堵塞狀態,除非讀取到信息。

計算結果文本框.setText(s);
}
catch(IOException e)
{ 計算結果文本框.setText("與伺服器已斷開");
break;
}
}
}
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==計算)
{ String s=輸入三邊長度文本框.getText();
if(s!=null)
{ try { out.writeUTF(s);
}
catch(IOException e1){}
}
}
}
}

(2) 伺服器端
import java.io.*;import java.net.*;
import java.util.*;import java.sql.*;
public class Computer_server
{ public static void main(String args[])
{ ServerSocket server=null;Server_thread thread;
Socket you=null;
while(true)
{ try{ server=new ServerSocket(4331);
}
catch(IOException e1)
{ System.out.println("正在監聽"); //ServerSocket對象不能重復創建。
}
try{ you=server.accept();
System.out.println("客戶的地址:"+you.getInetAddress());
}
catch (IOException e)
{ System.out.println("正在等待客戶");
}
if(you!=null)
{ new Server_thread(you).start(); //為每個客戶啟動一個專門的線程。
}
else
{ continue;
}
}
}
}
class Server_thread extends Thread
{ Socket socket;Connection Con=null;Statement Stmt=null;
DataOutputStream out=null;DataInputStream in=null;int n=0;
String s=null;
Server_thread(Socket t)
{ socket=t;
try { in=new DataInputStream(socket.getInputStream());
out=new DataOutputStream(socket.getOutputStream());
}
catch (IOException e)
{}
}
public void run()
{ while(true)
{ double a[]=new double[3] ;int i=0;
try{ s=in.readUTF();堵塞狀態,除非讀取到信息。

StringTokenizer fenxi=new StringTokenizer(s," ,");
while(fenxi.hasMoreTokens())
{ String temp=fenxi.nextToken();
try{ a[i]=Double.valueOf(temp).doubleValue();i++;
}
catch(NumberFormatException e)
{ out.writeUTF("請輸入數字字元");
}
}
double p=(a[0]+a[1]+a[2])/2.0;
out.writeUTF(" "+Math.sqrt(p*(p-a[0])*(p-a[1])*(p-a[2])));
sleep(2);
}
catch(InterruptedException e){}
catch (IOException e)
{ System.out.println("客戶離開");
break;
}
}
}
}

這些例子都是Java2實用教程上的.

6. java中的socket客戶端的埠如何綁定

java中的socket客戶端只需用伺服器所在機器的ip以及伺服器的埠作為參數創建一個Socket對象就可以了,客戶端的代碼可以看下實例:
Socket socket = new Socket("168.160.12.42",9998);
或:
Socket socket = new Socket(InetAddress.getLocalHost(),5678); // 向主機名為InetAddress.getLocalHost()的伺服器申請連接

客戶機必須知道有關伺服器的IP地址,對於著一點Java也提供了一個相關的類InetAddress 該對象的實例必須通過它的靜態方法來提供,它的靜態方法主要提供了得到本機IP 和通過名字或IP直接得到InetAddress的方法。

in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(),true);

以上的程序代碼建立了一個Socket對象,這個對象連接到ip地址為168.160.12.42的主機上、埠為9998的伺服器對象。並且建立了輸入流和輸出流,分別對應伺服器的輸出和客戶端的寫入。

閱讀全文

與socketjava源代碼相關的資料

熱點內容
八卦匯總421頁pdf 瀏覽:286
android應用自動升級 瀏覽:747
遠程屏幕監控源碼 瀏覽:569
雲伺服器的ip怎麼查詢 瀏覽:155
大學c語言搜題app在哪裡下載 瀏覽:109
pdf文檔被保護 瀏覽:345
有沒有電腦公司網站源碼下載 瀏覽:230
智能電視哪個app看電影好用 瀏覽:224
微信頁面源碼下載 瀏覽:957
怎麼看5代噴頭加密 瀏覽:359
linux查找文件並刪除文件 瀏覽:872
單片機里的編程軟體 瀏覽:164
鑽石投票網站源碼 瀏覽:973
cidrphp 瀏覽:882
android測試用例文檔 瀏覽:820
單片機素數 瀏覽:838
怎麼在桌面上發送文件夾 瀏覽:759
海外貸款源碼 瀏覽:717
北航單片機實驗 瀏覽:799
私有雲伺服器在哪裡 瀏覽:939